Using Recycler View to select element from a list

Ethan Beardsley :

For an Assignment I need to use a click on recycler view, with this click I am presented with 2 options in a dialog box. These are edit & delete. Basically my problem is I don't know how to get the position of the click. So I can't get the details for that recipe (class name). I have used LiveData> as this is what the assignment says to use.

The Problems I having are: 1. I don't know how to use the position to get the correct recipe from the Recipe class. 2. I need to use List not ArrayList

Here is my Main Activity Class

 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);
            }
        });

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, newRecipeActivity.class);
                startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);
            }
        });

}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
        Recipe recipe = new Recipe(data.getStringExtra(newRecipeActivity.EXTRA_REPLY));
        RecipeViewModel.insert(recipe);
    } else {
        Toast.makeText(
                getApplicationContext(),
                R.string.empty_not_saved,
                Toast.LENGTH_LONG).show();
    }
}


@Override
public void onItemClick(int position) {
    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);
            startActivity(update);
        }
    });
    alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //Delete

        }
    });
    alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
    alertDialog.show();
}
}

Here is my adapter class

 public class RecipeListAdapter extends 
 RecyclerView.Adapter<RecipeListAdapter.RecipeViewHolder> {
private OnItemClickListener mListener;
private LiveData<List<Recipe>> recipeList;



public interface OnItemClickListener{
    void onItemClick(int position);

}
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);
                    }
                }
            }
        });
    }
}

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{}

} Here is my View Model class

 public class RecipeViewModel extends AndroidViewModel {

private static RecipeRepository repo;
private LiveData<List<Recipe>> mAllRecipes;

public RecipeViewModel(Application application){
    super(application);
    repo = new RecipeRepository(application);
    mAllRecipes = repo.getAllRecipes();
}
LiveData<List<Recipe>> getAllRecipes() { return mAllRecipes; }
public static void insert(Recipe recipe) { repo.insert(recipe);}

public void getRecipe(int position) {

}
}
Adarsh Yashvanth :

Declare a list in MainActivity

List<Recipe> recipesList = new ArrayList<>();

Initialize that list with your recipes

mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
            @Override
            public void onChanged(@Nullable final List<Recipe> recipes) {
                recipesList = recipes; //init here
                adapter.setWords(recipes);
            }
        });

Use position to get the particular item you want to edit or delete

@Override
public void onItemClick(int position) {
    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) {

            recipesList.get(position); //returns the clicked item
            Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
            startActivity(update);
        }
    });
    alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //Delete
            recipesList.get(position); //returns the clicked item
        }
    });
    alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
    alertDialog.show();
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=388442&siteId=1