RecyclerView using item from a Realm database crashes - java

I have a fragment that is suppose to show a list of Game objects. When the fragment starts, I read all the Game objects from the database and add them to a List. It all works fine until the size of the list reaches 12. If it does, the App crashes even before the fragment is shown. If the list is bigger than 13 then it only crashes if I scroll all the way down and try and show the Games that are below.
Any ideas on what could cause this? I don´t really believe the RecyclerView is the problem.
Here are my classes. Please let me know if you need more information.
Any help would be very welcome.
My Game class
public class Game extends RealmObject{
#PrimaryKey
private long id;
private RealmList<Coordinates> mGameCoordinates;
private RealmList<Coordinates> mDrinkingStopsCoordinates;
private RealmList<Team> mTeams;
private String mDate;
private boolean mIsGameFinished;
private long mStartTime;
private long mFinishTime;
private long mTimeTaken;
public Game(RealmList<Team> teams, String date, long id) {
mTeams = teams;
mDate = date;
this.id = id;
}
public int getGameSize(){
int size = mTeams.size();
return size;
}
public String getDate() {
return mDate;
}
public void setDate(String date) {
mDate = date;
}
public RealmList<Team> getTeams() {
return mTeams;
}
public void setTeams(RealmList<Team> teams) {
mTeams = teams;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
//Default empty constructor - must be present
public Game(){
}
public RealmList<Coordinates> getDrinkingStopsCoordinates() {
return mDrinkingStopsCoordinates;
}
public void setDrinkingStopsCoordinates(RealmList<Coordinates> drinkingStopsCoordinates) {
mDrinkingStopsCoordinates = drinkingStopsCoordinates;
}
public RealmList<Coordinates> getGameCoordinates() {
return mGameCoordinates;
}
public void setGameCoordinates(RealmList<Coordinates> gameCoordinates) {
mGameCoordinates = gameCoordinates;
}
public long getStartTime() {
return mStartTime;
}
public void setStartTime(long startTime) {
mStartTime = startTime;
}
public long getFinishTime() {
return mFinishTime;
}
public void setFinishTime(long finishTime) {
mFinishTime = finishTime;
}
public long getTimeTaken() {
mTimeTaken = mFinishTime - mStartTime;
return mTimeTaken;
}
public void setTimeTaken(long timeTaken) {
mTimeTaken = timeTaken;
}
public boolean isGameFinished() {
return mIsGameFinished;
}
public void setGameFinished(boolean gameFinished) {
mIsGameFinished = gameFinished;
}
}
My Fragment
public class OldGameFragment extends Fragment {
private static final String TAG = "OldGameFragment";
private RecyclerView mRecyclerView;
private TextView mTextViewPlayers;
private TextView mTextViewDate;
private RecyclerAdapter mRecyclerAdapter;
private Toolbar myToolbar;
private String mStringReadyToShow;
private List<Game> mGames;
private RealmResults<Game> playerRealmResults;
private List<Game> mGameRealmList = new ArrayList<>();
private Realm mRealm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_old_game, container,false);
//DB
mRealm = Realm.getDefaultInstance();
//Singleton
ActivityStateSingleton activityStateSingleton = ActivityStateSingleton.getInstance();
activityStateSingleton.setActivityFlag(1);
mRecyclerView = (RecyclerView)v.findViewById(R.id.recyclerview_player_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Toolbar
myToolbar = (Toolbar)v.findViewById(R.id.my_toolbar_old_game);
myToolbar.setTitle(R.string.drawer_old_game);
myToolbar.setTitleTextColor(0xffffffff);
((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
readFromDB();
return v;
}
//Fragment
public static OldGameFragment newInstance(){
return new OldGameFragment();
}
public void readFromDB(){
RealmResults<Game> playerRealmResults = mRealm.where(Game.class).findAll();
int count = 0;
for(Game game : playerRealmResults){
mGameRealmList.add(game);
count++;
Log.d(TAG, "Count " + count);
}
mRecyclerAdapter = new RecyclerAdapter(mGameRealmList);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getContext()));
mRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(long id) {
Intent intent = GameOverviewActivity.toGameOverview(getActivity(), id);
startActivity(intent);
}
});
mRecyclerAdapter.notifyDataSetChanged();
}
/*RecyclerView*/
public class RecyclerHolder extends RecyclerView.ViewHolder {
private Game mGame;
private SwipeRevealLayout mSwipeRevealLayout;
private View mDeleteView;
public RecyclerHolder(View itemView) {
super(itemView);
mTextViewPlayers = (TextView)itemView.findViewById(R.id.list_item_player_teams);
mTextViewDate = (TextView)itemView.findViewById(R.id.list_item_date);
mSwipeRevealLayout = (SwipeRevealLayout)itemView.findViewById(R.id.swipe_layout);
mDeleteView = (View) itemView.findViewById(R.id.delete_layout);
}
public void bindPlayer(Game game){
mGame = game;
String name = game.getTeams().get(0).getTeamName();
int num = game.getTeams().get(0).getPlayers().size();
String text = name + "(" + num + ")";
for(Team t : game.getTeams()){
if(!text.contains(t.getTeamName())){
name = t.getTeamName();
num = t.getPlayers().size();
text += " vs. " + name + "(" + num + ")";
}
mDeleteView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getContext(),
R.style.AlertDialogCustom));
builder.setTitle(R.string.dialog_alert_title).setMessage(R.string.delete_game)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mRecyclerAdapter.dismissGame(getAdapterPosition(), mGames.get(getAdapterPosition()).getId());
}
}).setNegativeButton("Nein", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "No", Toast.LENGTH_SHORT).show();
}
});
AlertDialog dialog = builder.create();
dialog.show();
//So it won´t show the white borders around the round egdges
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
});
}
mTextViewPlayers.setText(text);
String date = getResources().getString(R.string.date) + game.getDate();
String space = " ";
mTextViewDate.setText(space + date);
}
}
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerHolder>{
/* This object helps you save/restore the open/close state of each view*/
private final ViewBinderHelper mViewBinderHelper = new ViewBinderHelper();
private OnItemClickListener mOnItemClickListener;
public RecyclerAdapter(List<Game> realmResults){
mGames = realmResults;
/*To only open one row at the time*/
mViewBinderHelper.setOpenOnlyOne(true);
}
#Override
public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View v = layoutInflater.inflate(
R.layout.list_item_game_rows, parent, false);
return new RecyclerHolder(v);
}
#Override
public void onBindViewHolder(RecyclerHolder holder, final int position) {
final Game game = mGames.get(position);
final String data = mGames.get(position).toString();
// You need to provide a String id which uniquely defines the data object.
mViewBinderHelper.bind(holder.mSwipeRevealLayout, data);
holder.bindPlayer(game);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnItemClickListener.onItemClick(game.getId());
}
};
mTextViewDate.setOnClickListener(listener);
mTextViewPlayers.setOnClickListener(listener);
}
#Override
public int getItemCount() {
return mGames.size();
}
/*Dismiss Game*/
public void dismissGame(int position, final long id){
mGames.remove(position);
this.notifyItemRemoved(position);
mRealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Game> gameRealmResults = mRealm.where(Game.class).equalTo("id", id).findAll();
gameRealmResults.deleteAllFromRealm();
}
});
}
public OnItemClickListener getOnItemClickListener(){
return mOnItemClickListener;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener){
this.mOnItemClickListener = onItemClickListener;
}
}
}
EDIT:
Here is the Log:
FATAL EXCEPTION: main Process: bosseln.swenden.de.bosseln, PID: 23424
Theme: themes:{default=overlay:com.init.designloper.init_v001, iconPack:com.init.designloper.init_v001, fontPkg:com.init.designloper.init_v001, com.android.systemui=overlay:com.init.designloper.init_v001, com.android.systemui.navbar=overlay:com.init.designloper.init_v001}
java.lang.ArrayIndexOutOfBoundsException: rowIndex > available rows: 0 > 0
at io.realm.internal.LinkView.nativeGetTargetRowIndex(Native Method)
at io.realm.internal.LinkView.getTargetRowIndex(LinkView.java:81)
at io.realm.RealmList.get(RealmList.java:448)
at bosseln.swenden.de.bosseln.fragments.OldGameFragment$RecyclerHolder.bindPlayer(OldGameFragment.java:149)
at bosseln.swenden.de.bosseln.fragments.OldGameFragment$RecyclerAdapter.onBindViewHolder(OldGameFragment.java:223)
at bosseln.swenden.de.bosseln.fragments.OldGameFragment$RecyclerAdapter.onBindViewHolder(OldGameFragment.java:195)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6279)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6312)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5258)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5521)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5363)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5359)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2141)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1525)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3506)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3254)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3767)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1735)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1579)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1488)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1735)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1579)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1488)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2934)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.

Please check the rows in the database, I think there may be some null value you are getting at row number 13.

Related

ListView or false method to get the result

package eu.andykrzemien.dog4u;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
class Size {
private int id;
private String SizeName;
public Size(int id, String sizeName) {
this.id = id;
SizeName = sizeName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSizeName() {
return SizeName;
}
public void setSizeName(String sizeName) {
SizeName = sizeName;
}
public String toString(){
return getId()+" "+getSizeName();
}
}
class Activities {
private int id;
private String ActivityName;
public Activities(int id, String activityName) {
this.id = id;
ActivityName = activityName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String toString() {
return getId()+ " "+getActivityName();
}
}
class Children {
private int id;
private String ChildrenName;
public Children(int id, String childrenName) {
this.id = id;
ChildrenName = childrenName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getChildrenName() {
return ChildrenName;
}
public void setChildrenName(String childrenName) {
ChildrenName = childrenName;
}
public String toString() {
return getId()+" "+getChildrenName();
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView sizeList;
ListView activityList;
ListView childrenList;
Button button;
public static final String TAG = "MyActivity";
public void inItListViews() {
sizeList= findViewById(R.id.sizeList);
activityList= findViewById(R.id.activityList);
childrenList= findViewById(R.id.childrenList);
}
public void dogMatches() {
Size s1 = new Size(1,"Miniature");
Size s2 = new Size(2,"Small");
Size s3 = new Size(3,"Medium");
Size s4 = new Size(4,"Large");
Size s5 = new Size(5,"Giant");
Size [] size = new Size[]{s1,s2,s3,s4,s5};
ArrayAdapter<Size> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,size);
this.sizeList.setAdapter(adapter1);
Activities a1 = new Activities(1,"Lazy");
Activities a2 = new Activities(2,"Light Active");
Activities a3 = new Activities(3,"Very Active");
Activities[] activities = new Activities[]{a1,a2,a3};
ArrayAdapter<Activities> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,activities);
this.activityList.setAdapter(adapter2);
Children c1 = new Children(1,"Like");
Children c2 = new Children(2,"Doesn't matter");
Children[] children = new Children[]{c1,c2};
ArrayAdapter<Children> adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1,children);
this.childrenList.setAdapter(adapter3);
}
public void processResult() {
Log.d(TAG,"Result button clicked");
int pos1= sizeList.getCheckedItemPosition();
int pos2 = activityList.getCheckedItemPosition();
int pos3 = childrenList.getCheckedItemPosition();
Size sSelected= (Size) sizeList.getItemAtPosition(pos1);
Activities aSelected=(Activities) activityList.getItemAtPosition(pos2);
Children cSelected=(Children) childrenList.getItemAtPosition(pos3);
if(sSelected!=null && aSelected!=null && cSelected!=null){
Log.d(TAG,"result "+ sSelected.getSizeName()+" : "+ aSelected.getActivityName()+ " " + cSelected.getChildrenName());
String petSeeker = yourBest(sSelected,aSelected,cSelected);
Toast.makeText(this,petSeeker,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Please Select Something",Toast.LENGTH_SHORT).show();
}
}
public void buttonPressed() {
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processResult();
}
});
}
private String yourBest(Size s, Activities a, Children c) {
String doThis;
if(s.getSizeName().equalsIgnoreCase("small")
&& a.getActivityName().equalsIgnoreCase("lazy")
&& c.getChildrenName().equalsIgnoreCase("like")){
Toast.makeText(this,"Chihuahua",Toast.LENGTH_LONG).show();
doThis="Chihuahua";
}
else if(s.getSizeName().equalsIgnoreCase("small")
&& a.getActivityName().equalsIgnoreCase("light active")
&& c.getChildrenName().equalsIgnoreCase("like")){
doThis="Labrador";
} else{
doThis="Find a cat";
}
return doThis;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inItListViews();
dogMatches();
buttonPressed();
}
#Override
public void onClick(View v) {
}
}
The app is running but the problem is that I can't get the result of three listViews. Is it something with the ListView or with the method? After pressing button I get only else message. Maybe there is some method to check the listView because maybe they aren't coded with the press of the mouse. I'm really stuck and need at least some advice not a ready solution.
Instead of using getCheckedItemPosition() to get the position of the selected list item, use listView.setOnItemClickListener()
So you can remove below statements, and make po1-pos3 as global fields
int pos1= sizeList.getCheckedItemPosition();
int pos2 = activityList.getCheckedItemPosition();
int pos3 = childrenList.getCheckedItemPosition();
As below:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
int pos1, pos2, pos3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inItListViews();
dogMatches();
buttonPressed();
sizeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos1 = position;
}
});
activityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos2 = position;
}
});
childrenList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos3 = position;
}
});
}
And to get a list item for a position:
sizeList.getAdapter().getItem(pos1);
activityList.getAdapter().getItem(pos2);
childrenList.getAdapter().getItem(pos3);
First of all I think it will be better without implementing View.OnClickListener, because you don't use it. Second - you can put a breakpoint at:
int pos1 = sizeList.getCheckedItemPosition();
Debug it and then you will see what is going wrong.
And last, I suggest creating a custom interface that will allow you to find out what position was checked.

How to get details when clicking on an item in a RecyclerView?

I am trying to get the details of the Recipe from which Recipe I have clicked in recycler view. I am using this to go to an edit/delete feature. Here is the code for my main activity.
The details that I am trying to get is getting the Name, Ingredients and method.
public class MainActivity extends AppCompatActivity implements RecipeListAdapter.OnItemClickListener {
private RecipeViewModel mRecipeViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
public String Name;
public String Ingredients;
public String Method;
private RecipeListAdapter mAdapter;
private RecipeDao recDao;
private LiveData<List<Recipe>> RecipeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final RecipeListAdapter adapter = new RecipeListAdapter(this);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
#Override
public void onChanged(#Nullable final List<Recipe> recipes) {
// Update the cached copy of the words in the adapter.
adapter.setWords(recipes);
}
});
void onItemClick(int position) {
//Delete Below test to pass data through
Recipe recipe = new Recipe("Test", "Yeet", "Jim");
// showAlertDialogBox();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Edit or Delete...");
alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
update.putExtra("Name", recipe.getName());
update.putExtra("Ingredients", recipe.getIngredients());
update.putExtra("Method", recipe.getMethod());
startActivity(update);
}
});
alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Delete
}
});
alertDialog.show();
}
Here is the Recipe.class if you needed it!
#Entity(tableName = "recipe_table")
public class Recipe {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name= "recipeId")
private int RecipeId;
private String name;
private String Ingredients;
private String Method;
#Ignore
public Recipe(String name, String Ingredients, String Method) {
this.RecipeId = RecipeId;
this.name = name;
this.Ingredients = Ingredients;
this.Method = Method;
}
public Recipe(String name) {
this.name = name;
}
public void changeText1(String text){
name = text;
}
//Add Image somehow!
public int getRecipeId() {
return RecipeId;
}
public void setRecipeId(int recipeId) {
RecipeId = recipeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
public String getIngredients() {
return Ingredients;
}
public void setIngredients(String ingredients) {
Ingredients = ingredients;
}
}
If you need anymore files, these are the files I have:
- RecipeListAdapter
- RecipeDao
- RecipeRepository
- RecipeRoomDatabase
- RecipeViewModel
Recipe Adapter code
public class RecipeListAdapter extends RecyclerView.Adapter {
private OnItemClickListener mListener;
private List recipeList;
public interface OnItemClickListener{
void onItemClick(int position, Recipe recipe);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
class RecipeViewHolder extends RecyclerView.ViewHolder {
private final TextView recipeItemView;
private RecipeViewHolder(View itemView) {
super(itemView);
recipeItemView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position,
recipeList.get(getAdapterPosition()));
}
}
}
});
}
}
private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words
RecipeListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.recipeList = recipeList;
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_item, parent,
false);
return new RecipeViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
if (mRecipes != null) {
Recipe current = mRecipes.get(position);
holder.recipeItemView.setText(current.getName());
} else {
// Covers the case of data not being ready yet.
holder.recipeItemView.setText("No Recipes");
}
}
void setWords(List<Recipe> recipes){
mRecipes = recipes;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't
return null).
#Override
public int getItemCount() {
if (mRecipes != null)
return mRecipes.size();
else return 0;
}
public interface OnNoteListener{}
}
Inside the onItemClick there is one more parameter need to add.
void onItemClick(int position, Recipe recipe) {
//Delete selected recipe from recipe list
arrayList.remove(recipe)
}
The onItemClick method will get called from adapter, from there you have to pass the selected receipe. In the adapter you have to use recipeList.get(getAdapterPosition()) to get the clicked receipe and pass this to the interface method, onItemClick along with the position.
So your code will look like this way inside the adapter,
itemClickListener.onItemClick(position,
recipeList.get(getAdapterPosition()))
Just as a note, please ensure instead of List, you need to take ArrayList to perform remove operation.

Search filter on listview of item returns wrong results on item click,

I have a listview getting filtered by an edit text on top. However, when I click on the item searched I get the result of another item being selected.
I Know similar questions are asked and answered by many already, but I went through all the forum but I am breaking my head from long back and sorry newbie much.
Any help will be appreciated.
My adapter:
public class Srv_Adapter extends RecyclerView.Adapter<Srv_Adapter.MyViewHolder> implements Filterable {
List<Srv_Pets> pets, srvPetsFilter;
private Context context;
private RecyclerViewClickListener mListener;
Srv_CustomFilter filter;
public Srv_Adapter(List<Srv_Pets> pets, Context context, RecyclerViewClickListener listener) {
this.pets = pets;
this.srvPetsFilter = pets;
this.context = context;
this.mListener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_srv, parent, false);
return new MyViewHolder(view, mListener);
}
#SuppressLint("CheckResult")
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.mName.setText(pets.get(position).getName());
holder.mType.setText(pets.get(position).getModel() + " / "
+ pets.get(position).getCreated_by());
holder.mDate.setText(pets.get(position).getBirth());
RequestOptions requestOptions = new RequestOptions();
requestOptions.skipMemoryCache(true);
requestOptions.diskCacheStrategy(DiskCacheStrategy.NONE);
requestOptions.placeholder(R.drawable.logo);
requestOptions.error(R.drawable.logo);
Glide.with(context)
.load(pets.get(position).getPicture())
.apply(requestOptions)
.into(holder.mPicture);
final Boolean love = pets.get(position).getLove();
if (love){
holder.mLove.setImageResource(R.drawable.likeon);
} else {
holder.mLove.setImageResource(R.drawable.likeof);
}
}
#Override
public int getItemCount() {
return pets.size();
}
#Override
public Filter getFilter() {
if (filter==null) {
filter=new Srv_CustomFilter((ArrayList<Srv_Pets>) srvPetsFilter,this);
}
return filter;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private RecyclerViewClickListener mListener;
private CircleImageView mPicture;
private ImageView mLove;
private TextView mName, mType, mDate;
private RelativeLayout mRowContainer;
public MyViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
mPicture = itemView.findViewById(R.id.picture);
mName = itemView.findViewById(R.id.name);
mType = itemView.findViewById(R.id.type);
mLove = itemView.findViewById(R.id.love);
mDate = itemView.findViewById(R.id.date);
mRowContainer = itemView.findViewById(R.id.row_container);
mListener = listener;
mRowContainer.setOnClickListener(this);
mLove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.row_container:
mListener.onRowClick(mRowContainer, getAdapterPosition());
break;
case R.id.love:
mListener.onLoveClick(mLove, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowClick(View view, int position);
void onLoveClick(View view, int position);
}
}
Search Menu Activity
public class Service_Main extends AppCompatActivity{
SharedPreferences prf;
Intent intent;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private Srv_Adapter srvAdapter;
private List<Srv_Pets> srvPetsList;
Srv_ApiInterface srvApiInterface;
Srv_Adapter.RecyclerViewClickListener listener;
ProgressBar progressBar;
private String userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_main);
srvApiInterface = Srv_ApiClient.getApiClient().create(Srv_ApiInterface.class);
progressBar = findViewById(R.id.progress);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
TextView result = (TextView)findViewById(R.id.result);
recyclerView.setLayoutManager(layoutManager);
prf = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(Service_Main.this, loginActivity.class);
userInfo = prf.getString("username",null);
listener = new Srv_Adapter.RecyclerViewClickListener() {
private Srv_Pets getIteamposition(int position)
{
return srvPetsList.get(position);
}
#Override
public void onRowClick(View view, final int position) {
Intent intent = new Intent(Service_Main.this, Service_edit.class);
intent.putExtra("id", srvPetsList.get(position).getId());
intent.putExtra("name", srvPetsList.get(position).getName());
intent.putExtra("species", srvPetsList.get(position).getSpecies());
intent.putExtra("jobcard", srvPetsList.get(position).getJobcard());
intent.putExtra("model_code", srvPetsList.get(position).getModel_code());
intent.putExtra("picture", srvPetsList.get(position).getPicture());
intent.putExtra("birth", srvPetsList.get(position).getBirth());
intent.putExtra("entry_mode", srvPetsList.get(position).getEntry_mode());
intent.putExtra("pickup_done_by_code", srvPetsList.get(position).getPickup_done_by_code());
intent.putExtra("drop_mode", srvPetsList.get(position).getDrop_mode());
intent.putExtra("service_type", srvPetsList.get(position).getDrop_mode());
intent.putExtra("drop_done_by_code", srvPetsList.get(position).getDrop_done_by_code());
intent.putExtra("pick_emp_name", srvPetsList.get(position).getPick_emp_name());
intent.putExtra("drop_emp_name", srvPetsList.get(position).getDrop_emp_name());
startActivity(intent);
final int id = srvPetsList.get(position).getId();
final Boolean love = srvPetsList.get(position).getLove();
final ImageView mLove = view.findViewById(R.id.love);
if (love){
mLove.setImageResource(R.drawable.likeof);
srvPetsList.get(position).setLove(false);
updateLove("Rd_status", id, false);
srvAdapter.notifyDataSetChanged();
} else {
mLove.setImageResource(R.drawable.likeon);
srvPetsList.get(position).setLove(true);
updateLove("Rd_status", id, true);
srvAdapter.notifyDataSetChanged();
}
}
#Override
public void onLoveClick(View view, int position) {
// final int id = srvPetsList.get(position).getId();
// final Boolean love = srvPetsList.get(position).getLove();
// final ImageView mLove = view.findViewById(R.id.love);
// if (love){
// mLove.setImageResource(R.drawable.likeof);
// srvPetsList.get(position).setLove(false);
// updateLove("Rd_status", id, false);
// srvAdapter.notifyDataSetChanged();
// } else {
// mLove.setImageResource(R.drawable.likeon);
// srvPetsList.get(position).setLove(true);
// updateLove("Rd_status", id, true);
// srvAdapter.notifyDataSetChanged();
// }
}
};
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Service_Main.this, Service_edit.class));
}
});
FloatingActionButton fab1 = findViewById(R.id.log_out);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Service_Main.this, HomePage.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName())
);
searchView.setQueryHint("Search Pet...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(final String query) {
srvAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
srvAdapter.getFilter().filter(newText);
return false;
}
});
searchMenuItem.getIcon().setVisible(false, false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getPets(){
String username = userInfo;
Call<List<Srv_Pets>> call = srvApiInterface.getPets(username);
call.enqueue(new Callback<List<Srv_Pets>>() {
#Override
public void onResponse(Call<List<Srv_Pets>> call, Response<List<Srv_Pets>> response) {
progressBar.setVisibility(View.GONE);
srvPetsList = response.body();
Log.i(Service_Main.class.getSimpleName(), response.body().toString());
srvAdapter = new Srv_Adapter(srvPetsList, Service_Main.this, listener);
recyclerView.setAdapter(srvAdapter);
srvAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<Srv_Pets>> call, Throwable t) {
Toast.makeText(Service_Main.this, "rp :"+
t.getMessage().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
public void updateLove(final String key, final int id, final Boolean love){
String night_updated_by = userInfo;
String reg_num = userInfo;
Call<Srv_Pets> call = srvApiInterface.updateLove(key, id, love, night_updated_by, reg_num);
call.enqueue(new Callback<Srv_Pets>() {
#Override
public void onResponse(Call<Srv_Pets> call, Response<Srv_Pets> response) {
Log.i(Service_Main.class.getSimpleName(), "Response "+response.toString());
String value = response.body().getValue();
String message = response.body().getMassage();
if (value.equals("1")){
Toast.makeText(Service_Main.this, message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Service_Main.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Srv_Pets> call, Throwable t) {
Toast.makeText(Service_Main.this, t.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
getPets();
}
}
List of Items from PHP, MYSQL using Volly
package com.haerul.mypets.service;
import com.google.gson.annotations.SerializedName;
public class Srv_Pets {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
#SerializedName("species")
private String species;
#SerializedName("breed")
private String breed;
#SerializedName("model_code")
private int model_code;
#SerializedName("jobcard")
private int jobcard;
#SerializedName("birth")
private String birth;
#SerializedName("picture")
private String picture;
#SerializedName("love")
private Boolean love;
#SerializedName("value")
private String value;
#SerializedName("message")
private String massage;
#SerializedName("model")
private String model;
#SerializedName("entry_mode")
private int entry_mode;
#SerializedName("drop_mode")
private int drop_mode;
#SerializedName("pickup_done_by_code")
private String pickup_done_by_code;
#SerializedName("service_type")
private int service_type;
#SerializedName("drop_done_by_code")
private String drop_done_by_code;
#SerializedName("pick_emp_name")
private String pick_emp_name;
#SerializedName("drop_emp_name")
private String drop_emp_name;
#SerializedName("created_by")
private String created_by;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public int getModel_code() {
return model_code;
}
public void setModel_code(int gender) {
this.model_code = model_code;
}
public int getJobcard() {
return jobcard;
}
public void setJobcard(int jobcard) {
this.jobcard = jobcard;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public Boolean getLove() {
return love;
}
public void setLove(Boolean love) {
this.love = love;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMassage() {
return massage;
}
public void setMassage(String massage) {
this.massage = massage;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getEntry_mode(){
return entry_mode;
}
public void setEntry_mode(int entry_mode){
this.entry_mode = entry_mode;
}
public String getPickup_done_by_code() {
return pickup_done_by_code;
}
public void setPickup_done_by_code(String pickup_done_by_code) {
this.pickup_done_by_code = pickup_done_by_code;
}
public int getDrop_mode(){
return drop_mode;
}
public void setDrop_mode(int drop_mode){
this.drop_mode = drop_mode;
}
public int getService_type(){
return service_type;
}
public void setService_type(){
this.service_type = service_type;
}
public String getDrop_done_by_code(){
return drop_done_by_code;
}
public void setDrop_done_by_code(String drop_done_by_code){
this.pickup_done_by_code = drop_done_by_code;
}
public String getPick_emp_name(){
return pick_emp_name;
}
public void setPick_emp_name(String pick_emp_name){
this.pick_emp_name = pick_emp_name;
}
public String getDrop_emp_name(){
return drop_emp_name;
}
public void setDrop_emp_name(String drop_emp_name){
this.pick_emp_name = pick_emp_name;
}
public String getCreated_by(){
return created_by;
}
public void setCreated_by(String created_by){
this.created_by = created_by;
}
}

problem with getting items from database through intent

I developed a vocabulary app that has a Recycler View in main activity and shows two column of database: unit number and Unit name.When I click on each item it goes to another activity called inner page that has 6 text views and it must show other items of that row like word definition unit number spell meaning and part of speech. But unfortunately text views are empty and it shows only one value which is unit number.Please take a look at my codes and tell me what I missed.
Here's my codes:
Main page:
public class TabWord extends Fragment {
private RecyclerView recyclerView;
private ArrayList<WordItem> items = new ArrayList<>();
private WordTab adapter;
private DatabaseHelper databaseHelper;
private Cursor cursor ;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.tab_word, container, false);
recyclerView = viewGroup.findViewById(R.id.recyclerview_word);
adapter = new WordTab(items, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
loadDatabase();
return viewGroup;
}
public void loadDatabase() {
databaseHelper = new DatabaseHelper(getActivity());
try {
databaseHelper.checkAndCopyDatabase();
databaseHelper.openDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
try {
cursor = databaseHelper.QueryData("select * from ielts");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
WordItem item = new WordItem();
item.setUnitName(cursor.getString(2));
item.setUnitNumber(cursor.getString(1));
items.add(item);
} while (cursor.moveToNext());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new WordTab(items, getActivity());
adapter.setOnTapListener(new OnTapListener() {
#Override
public void OnTapView(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
}
Adapter:
public class WordTab extends RecyclerView.Adapter<WordTab.ViewHolder> {
public static List<WordItem> wordItems;
private Context context;
private OnTapListener onTapListener;
public WordTab(List<WordItem> wordItems, Context context) {
this.wordItems = wordItems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_word, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
WordItem wordItem = wordItems.get(position);
holder.unitNumber.setText(wordItem.getUnitNumber());
holder.unitName.setText(wordItem.getUnitName());
holder.cardView.setId(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onTapListener != null) {
onTapListener.OnTapView(position);
int position = v.getId();
Intent intent = new Intent(context, InnerPage.class);
intent.putExtra("name", "words");
intent.putExtra("id", position + "");
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return wordItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView unitName, unitNumber;
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
unitName = itemView.findViewById(R.id.unit_name);
unitNumber = itemView.findViewById(R.id.unit_number);
cardView= itemView.findViewById(R.id.card_view_word);
}
}
public void setOnTapListener(OnTapListener onTapListener) {
this.onTapListener = onTapListener;
}
}
Model:
public class WordItem {
private int id;
private String unitNumber;
private String unitName;
private String word;
private String phonetic,pos,persian,definition;
public WordItem() {
this.unitName = unitName;
this.unitNumber = unitNumber;
this.word = word;
this.phonetic = phonetic;
this.pos = pos;
this.persian = persian;
this.definition = definition;
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public String getPersian() {
return persian;
}
public void setPersian(String persian) {
this.persian = persian;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(String unitNumber) {
this.unitNumber = unitNumber;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
}
Inner Page:
public class InnerPage extends AppCompatActivity {
private int id;
private String unitNumber,word,phonetic,pos,persian,definition;
private TextView unitTxt,wordTxt,phoneticTxt,posTxt,persianTxt,definitionTxt;
private int layoutId;
private String pageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inner_page);
Bundle extras = getIntent().getExtras();
if (extras != null) {
layoutId = Integer.parseInt(extras.getString("id"));
pageName = extras.getString("name");
if (pageName.equals("words")){
id = WordTab.wordItems.get(layoutId).getId();
unitNumber = WordTab.wordItems.get(layoutId).getUnitNumber();
word = WordTab.wordItems.get(layoutId).getWord();
phonetic = WordTab.wordItems.get(layoutId).getPhonetic();
pos = WordTab.wordItems.get(layoutId).getPos();
persian = WordTab.wordItems.get(layoutId).getPersian();
definition = WordTab.wordItems.get(layoutId).getDefinition();
}
}
unitTxt = findViewById(R.id.unit);
wordTxt = findViewById(R.id.word);
phoneticTxt = findViewById(R.id.phonetic);
posTxt = findViewById(R.id.txtSpell);
persianTxt = findViewById(R.id.farMean);
definitionTxt = findViewById(R.id.definition);
unitTxt.setText(unitNumber);
wordTxt.setText(word);
phoneticTxt.setText(phonetic);
posTxt.setText(pos);
persianTxt.setText(persian);
definitionTxt.setText(definition);
}
}

Android RecylerView Add Button gives me error

I'm trying to add a Button which when clicked should open a new Activity. Despite spending a long time on this, my efforts have been unsuccessful. If I add the OnClickListener and click the Button it gives me an error. Thank you for your help.
Listele.Java
package com.example.hp.myapplication;
import android.view.View;
import android.widget.Button;
public class Listele {
private String adi;
private String fiyat;
private String aciklama;
private String stok;
private String resim;
public Listele(String adi, String fiyat, String aciklama, String stok,String resim) {
this.adi = adi;
this.fiyat = fiyat;
this.aciklama = aciklama;
this.stok = stok;
this.resim = resim;
}
//getters and setters
#Override
public String toString() {
return "Listele{" +
"adi='" + adi + '\'' +
", fiyat='" + fiyat + '\'' +
", aciklama='" + aciklama + '\'' +
", stok='" + stok + '\'' +
", resim='" + resim + '\'' +
'}';
}
}
ListeleAdapter.Java
package com.example.hp.myapplication;
//imports
public class ListeleAdapter extends RecyclerView.Adapter<ListeleAdapter.urunlistem> {
private Context contexto;
private ArrayList<Listele>tortica;
public ListeleAdapter(ArrayList<Listele> tortica, Context contexto ) {
this.contexto = contexto;
this.tortica = tortica;
}
#Override
public urunlistem onCreateViewHolder(ViewGroup parent, int viewType) {
return new urunlistem(LayoutInflater.from(parent.getContext()).inflate(R.layout.list,null));
}
#Override
public void onBindViewHolder(urunlistem holder, int position) {
holder.adi.setText(tortica.get(position).getAdi());
holder.aciklama.setText(tortica.get(position).getAciklama());
holder.stok.setText(tortica.get(position).getStok());
holder.fiyat.setText(tortica.get(position).getFiyat());
Glide.with(contexto).load("http://192.168.1.33:8080/urunler/"+tortica.get(position).getResim()).into(holder.tresim);
}
#Override
public int getItemCount() {
return tortica.size();
}
public static class urunlistem extends RecyclerView.ViewHolder{
ImageView tresim;
TextView adi,fiyat,stok,aciklama;
Button sepete_ekle;
ArrayList<Listele> listeles = new ArrayList<Listele>();
public urunlistem(View itemView) {
super(itemView);
tresim=(ImageView)itemView.findViewById(R.id.resim);
adi=(TextView)itemView.findViewById(R.id.adi_urun);
fiyat=(TextView)itemView.findViewById(R.id.fiyat);
stok=(TextView)itemView.findViewById(R.id.stok);
aciklama=(TextView)itemView.findViewById(R.id.aciklama);
}
}
}
MainActivity.Java
package com.example.hp.myapplication;
//imports
public class MainActivity extends AppCompatActivity {
private static final String url="http://192.168.1.33:8080/urunler/goruntule.php";
private RecyclerView recyclerView;
private ListeleAdapter adapter;
private ArrayList<Listele>listeles = new ArrayList<>();
ProgressDialog progressDialog;
RequestQueue requestQu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQu = Volley.newRequestQueue(getApplicationContext());
goster();
}
private void goster() {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Bilgiler alınıyor");
recyclerView=(RecyclerView) findViewById(R.id.listado);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false));
recyclerView.setHasFixedSize(true);
adapter = new ListeleAdapter(listeles,this);
recyclerView.setAdapter(adapter);
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i=0;i<response.length();i++)
{
try {
JSONObject object = response.getJSONObject(i);
String resimurl=object.getString("resim");
String adi=object.getString("adi");
String stok=object.getString("stok");
String fiyat=object.getString("fiyat");
String aciklama=object.getString("aciklama");
listeles.add(new Listele(adi,fiyat,aciklama,stok,resimurl));
} catch (JSONException e) {
Toast.makeText(MainActivity.this,""+e,Toast.LENGTH_LONG).show();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQu.add(request);
}
}
I didn't see your logcat but first of all you adding OnClickListener to your Button in wrong place. Add it in onBindViewHolder instead of ViewHolder constructor. In your code like that :
#Override
public void onBindViewHolder(urunlistem holder, int position) {
holder.adi.setText(tortica.get(position).getAdi());
holder.aciklama.setText(tortica.get(position).getAciklama());
holder.stok.setText(tortica.get(position).getStok());
holder.fiyat.setText(tortica.get(position).getFiyat());
Glide.with(contexto).load("http://192.168.1.33:8080/urunler/"+
tortica.get(position).getResim()).into(holder.tresim);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String salutation="Merhaba | Hello | Здравствуйте | Hallo | Salut";
Toast.makeText(mContext,salutation,Toast.LENGTH_SHORT).show();
}
});
}
It's because you never inflated the button in your ViewHolder class. Remember how were supposed to "find the view" when using views in java lol? Do that.
hope this help you
package com.example.hp.myapplication;
//imports
public class ListeleAdapter extends RecyclerView.Adapter<ListeleAdapter.urunlistem> {
private Context contexto;
private ArrayList<Listele>tortica;
public ListeleAdapter(ArrayList<Listele> tortica, Context contexto ) {
this.contexto = contexto;
this.tortica = tortica;
}
#Override
public urunlistem onCreateViewHolder(ViewGroup parent, int viewType) {
return new urunlistem(LayoutInflater.from(parent.getContext()).inflate(R.layout.list,null));
}
#Override
public void onBindViewHolder(urunlistem holder, int position) {
holder.adi.setText(tortica.get(position).getAdi());
holder.aciklama.setText(tortica.get(position).getAciklama());
holder.stok.setText(tortica.get(position).getStok());
holder.fiyat.setText(tortica.get(position).getFiyat());
Glide.with(contexto).load("http://192.168.1.33:8080/urunler/"+tortica.get(position).getResim()).into(holder.tresim);
}
#Override
public int getItemCount() {
return tortica.size();
}
//Step 1: Implement View.OnClickListener as below
public static class urunlistem extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView tresim;
TextView adi,fiyat,stok,aciklama;
Button sepete_ekle;
ArrayList<Listele> listeles = new ArrayList<Listele>();
public urunlistem(View itemView) {
super(itemView);
tresim=(ImageView)itemView.findViewById(R.id.resim);
adi=(TextView)itemView.findViewById(R.id.adi_urun);
fiyat=(TextView)itemView.findViewById(R.id.fiyat);
stok=(TextView)itemView.findViewById(R.id.stok);
aciklama=(TextView)itemView.findViewById(R.id.aciklama);
//Step 2: Register Your Button here below
sepete_ekle=(Button)itemView.findViewById(R.id.button);
sepete_ekle.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Step 3: Redirect to next Activity From here
Intent intent = new Intent(contexto, NextActivity.class);
contexto.startActivity(intent);
}
}
}

Categories