Open new activity from Recyclerview containing cards - java

Have an apparently simple task of -
Display a list of items using recycler view and each item should be card view.On click of any item new screen should open which shows detail of that item.
I already have seen various questions posted on the same topic, I would appreciate a little help on the attempt ive made rather than redirecting me there, since I'm pretty new and unable to understand how exactly to implement just by seeing those answers.I have tried to follow a tutorial closely but clearly have failed in replicating the results.HERE ARE THE FILES
MainActivity.java
. package com.example.hardikvats.recylerviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String[] phones={"MotoX","Nokia Asha","Lumia 710","Iphone 7s"};
private String[] OperatingSytem={"Android","Symbian","Windows","Ios"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
MyAdapter adapter=new MyAdapter(this,phones);
recyclerView.setAdapter(adapter);
}
}
MyAdapter.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] phones;
String[] OperatingSystem;
//CONSTRUCTOR
public MyAdapter(Context c, String[] PhoneModel){
this.c=c;
this.phones=PhoneModel;
//this.OperatingSystem=OperatingSystem;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//INFLATING FROM XML TO JAVA VIEW
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.PhoneModel.setText(phones[position]);
holder.setItemClickListner(new ItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
}
});
}
#Override
public int getItemCount() {
return phones.length;
}
}
MyHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView PhoneModel;
ItemClickListner icl;
public MyHolder(View itemView) {
super(itemView);
PhoneModel=(TextView) itemView.findViewById(R.id.MobilePhone);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.icl.onItemClick(v,getLayoutPosition());
}
public void setItemClickListner(ItemClickListner itemClickListner){
this.icl=itemClickListner;
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
TextView OperatingSystem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2);
Intent i=getIntent();
final String OperatingSystem =i.getExtras().getString("Operating System");
}
}
ItemClickListner.java(Interface)
`import android.view.View;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public interface ItemClickListner {
void onItemClick(View v, int position);
}`
The goal is to click each list item from phones array and get an activity listing the OS in a new activity in a new textfield

after i.putExtra("OS NAME ....
add this line
c.startActivity(c,DetailActivity.class);

As you did, in order that changes to be small, try this:
holder.PhoneModel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[holder.getAdapterPosition()]);
}
});
Holder will always retain your position.

//set on item click listener like this
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();
// here you can start your detail Activity
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
c.startActivity(i);
}
}));
// here is the on item click listener class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(),e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)){
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override`enter code here`
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}

Related

How do I set onClick listener to recyclerView?

I want to add onClick to recyclerView to send data back to form Activity for update data process. How can I implement onItemClickListner when this code doesn't have adapter in it?
Show_Employees.java:
package com.example.roomdatabaseandroid;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.roomdatabaseandroid.DataModel.EmployeeDao;
import com.example.roomdatabaseandroid.DataModel.EmployeeDatabase;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class ShowEmployees extends AppCompatActivity {
private static final int EDIT_COURSE_REQUEST = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_employees);
RecyclerView recyclerView;
FloatingActionButton fab = findViewById(R.id.idFABAdd);
EmployeeDao employeeDao;
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//starting a new activity for adding a new course and passing a constant value in it.
Intent intent = new Intent(ShowEmployees.this, MainActivity.class);
startActivity(intent);
}
});
employeeDao = EmployeeDatabase.getDBInstance(this).employeeDao();
recyclerView = findViewById(R.id.employeeRecyclerView);
EmployeeRecycler employeeRecycler = new EmployeeRecycler(employeeDao.getAllEmployee());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(employeeRecycler);
//below method is use to add swipe to delete method for item of recycler view.
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | 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) {
//on recycler view item swiped then we are deleting the item of our recycler view.
employeeDao.deleteEmployee(employeeRecycler.data.get(viewHolder.getAdapterPosition()));
Toast.makeText(ShowEmployees.this, "Employee deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
}
}
Employee_Recycler.java:
package com.example.roomdatabaseandroid;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.roomdatabaseandroid.DataModel.DataConverter;
import com.example.roomdatabaseandroid.DataModel.Employee;
import java.util.List;
public class EmployeeRecycler extends RecyclerView.Adapter<EmployeeViewHolder> {
List<Employee> data;
public EmployeeRecycler(List<Employee> employees){
data = employees;
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item_1,
parent,false
);
return new EmployeeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull EmployeeViewHolder holder, int position) {
Employee employee = data.get(position);
holder.imageView.setImageBitmap(DataConverter.convertByteArraytoImage(employee.getImage()));
holder.firstName.setText(employee.getFirstName());
holder.middleName.setText(employee.getMiddleName());
holder.lastName.setText(employee.getLastName());
holder.dob.setText(employee.getDOB());
holder.gender.setText(employee.getGender());
holder.address.setText(employee.getAddress());
holder.designation.setText(employee.getDesignation());
holder.email.setText(employee.getEmail());
holder.phoneNumber.setText(employee.getPhoneNumber());
}
#Override
public int getItemCount() {
return data.size();
}
}
EmployeeViewHolder.java:
package com.example.roomdatabaseandroid;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class EmployeeViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView firstName,middleName,lastName,email,phoneNumber,address,designation,gender,dob;
public EmployeeViewHolder(#NonNull View itemView) {
super(itemView);
firstName = itemView.findViewById(R.id.idTVFirstName);
middleName = itemView.findViewById(R.id.idTVMiddleName);
lastName = itemView.findViewById(R.id.idTVLastName);
dob = itemView.findViewById(R.id.idTVDOB);
address = itemView.findViewById(R.id.idTVAddress);
gender = itemView.findViewById(R.id.idTVGender);
designation = itemView.findViewById(R.id.idTVDesignation);
email = itemView.findViewById(R.id.idTVEmail);
phoneNumber = itemView.findViewById(R.id.idTVPhoneNumber);
imageView = itemView.findViewById(R.id.profileImageView);
}
}
add an interface
interface AdapterItemClickListener {
void onItemClickListener(Employee employee, int position)
}
your actvity must implement this interface
public class ShowEmployees extends AppCompatActivity implements AdapterItemClickListener {
private static final int EDIT_COURSE_REQUEST = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_employees);
RecyclerView recyclerView;
FloatingActionButton fab = findViewById(R.id.idFABAdd);
EmployeeDao employeeDao;
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//starting a new activity for adding a new course and passing a constant value in it.
Intent intent = new Intent(ShowEmployees.this, MainActivity.class);
startActivity(intent);
}
});
employeeDao = EmployeeDatabase.getDBInstance(this).employeeDao();
recyclerView = findViewById(R.id.employeeRecyclerView);
EmployeeRecycler employeeRecycler = new EmployeeRecycler(employeeDao.getAllEmployee(), this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(employeeRecycler);
//below method is use to add swipe to delete method for item of recycler view.
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | 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) {
//on recycler view item swiped then we are deleting the item of our recycler view.
employeeDao.deleteEmployee(employeeRecycler.data.get(viewHolder.getAdapterPosition()));
Toast.makeText(ShowEmployees.this, "Employee deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
}
void onItemClickListener(Employee employee, int position) {
//update or another job
}
}
and your adapter
public class EmployeeRecycler extends RecyclerView.Adapter<EmployeeViewHolder> {
List<Employee> data;
AdapterItemClickListener itemClickListener;
public EmployeeRecycler(List<Employee> employees, AdapterItemClickListener itemClickListener){
data = employees;
this.itemClickListener = itemClickListener;
}
#NonNull
#Override
public EmployeeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item_1,
parent,false
);
return new EmployeeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull EmployeeViewHolder holder, int position) {
Employee employee = data.get(position);
holder.imageView.setImageBitmap(DataConverter.convertByteArraytoImage(employee.getImage()));
holder.firstName.setText(employee.getFirstName());
holder.middleName.setText(employee.getMiddleName());
holder.lastName.setText(employee.getLastName());
holder.dob.setText(employee.getDOB());
holder.gender.setText(employee.getGender());
holder.address.setText(employee.getAddress());
holder.designation.setText(employee.getDesignation());
holder.email.setText(employee.getEmail());
holder.phoneNumber.setText(employee.getPhoneNumber());
holder.itemView.setOnClickListener (v -> {
itemClickListener.onItemClickListener(employee, position);
});
}
#Override
public int getItemCount() {
return data.size();
}
}

Click on one card view affected another card view value

When I create a custom card view in recycler view and click the increment button counter work properply. But when I crete another cardview then already created card counter value reset to 0. How to solve this issue?
Here's my Main Activity code
package com.example.muhasbaapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.example.muhasbaapp.CustomAdapter.ViewHolder.*;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter mAdapter,countAdapter;
private RecyclerView.LayoutManager layoutManager,layoutManager2;
private static RecyclerView recyclerView,recyclerView2;
private ImageView imageView;
public CustomModel customModel;
public static ArrayList<String> input = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView2=(RecyclerView)findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
recyclerView2.setHasFixedSize(true);
layoutManager2=new LinearLayoutManager(this);
recyclerView2.setLayoutManager(layoutManager2);
recyclerView2.setItemAnimator(new DefaultItemAnimator());
mAdapter= new CustomAdapter(input);
recyclerView2.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_action_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) { //add action2 kau kat sini
switch (item.getItemId()) {
case R.id.action_item_1:
openCustomDialoge();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openCustomDialoge() {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.user_generated_cards, null);
final EditText editText = (EditText) dialogView.findViewById(R.id.edt_comment);
Button button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
Button button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s=editText.getText().toString();
if (s.isEmpty()){
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
}else {
input.add(s);
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
dialogBuilder.setView(dialogView);
dialogBuilder.show();
}
}
And Here' my Adaptar Class code
package com.example.muhasbaapp;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
public ArrayList<String> values;
final CustomModel customMdl=new CustomModel();
final MainActivity mainActivity=new MainActivity();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView tv;
public View layout;
public TextView counter_value;
public ImageView increment,decrement, deleted;
public int counter;
public ViewHolder(View v) {
super(v);
layout = v;
tv = (TextView) v.findViewById(R.id.textViewName);
counter_value=(TextView) v.findViewById(R.id.counter);
increment=(ImageView)v.findViewById(R.id.increment);
decrement=(ImageView)v.findViewById(R.id.decrement);
deleted=(ImageView)v.findViewById(R.id.delbtn);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, values.size());
}
// Provide a suitable constructor (depends on the kind of dataset)
public CustomAdapter(ArrayList<String> myDataset) {
this.values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.custom_cards_layout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = values.get(position);
holder.tv.setText(name);
final int[] counter={0};
holder.deleted.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remove(position);
}
});
holder.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter[0] == 0) {
Toast.makeText(v.getContext(), "Can't add less than 0", Toast.LENGTH_SHORT).show();
} else {
counter[0] -= 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
}
});
holder.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.decrement.setEnabled(true);
counter[0] += 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
If anyone knows this problem please inform me.
Thanks in advance
Well, I'm seeing some bad practices in your code:
Adapters hosted in main activity must be not static, what do you think if try accessing via recyclerView.getAdapter()
Please remove the next one in your adapter
final MainActivity mainActivity = new MainActivity();
So the problem that you are having is inside your click listener.
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s = editText.getText().toString();
if (s.isEmpty()) {
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
} else {
input.add(s); // <-------------- HERE
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
You add the new item to the array, however, the adapter never knows that there is a new item has been added.
Access to the instanced adapter which has been attached to RecyclerView in onCreate() step and update their data.

Index out of Bound on Item deletion in a Recycler View's adapter

I am trying to create a note-taking app focusing on color-changing.
In one of the activity, I am trying to implement item addition and deletion to the note
picture_of_the_activity.
Item addition obviously works as intended.
The problem is with the deletion, it is very inconsistent: when I delete all the item starting from the last one upward, everything work fine; if I delete items in another order the adapter mess up, do not always delete the correct one and crashes when removing the last item.
I looked it up and found some possible solution (here or in other websites) but couldn't find a solution, or, so I thought.
I created methods inside the adapter addItem() and removeItem() so any changes is done within the class.
Maybe I am misunderstanding a concept or missing something?
Thank you in advance!
some interfaces or protion of the code are missing because I didn't implement some features yet
Activity Code
package com.example.colornoteplus;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
public class CheckListNoteActivity extends AppCompatActivity{
// note editable views
private EditText titleView;
private TextView titleCharacterCount;
private ImageButton colorView;
private RecyclerView contentView;
private FloatingActionButton fab;
CheckListAdapter adapter;
// toolbar
private Toolbar toolbar;
// Current note
private CheckListNote note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getNoteFromIntent();
note.getContent().add(new CheckListItem("ONE"));
note.getContent().add(new CheckListItem("TWO"));
note.getContent().add(new CheckListItem("THREE"));
note.getContent().add(new CheckListItem("FOUR"));
note.getContent().add(new CheckListItem("FIVE"));
changeViewsColor(0);
}
// Method used to add menus and configure button action
// like OnClickListeners ...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Create a submenu for sorting purpose
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_check_list_activity,menu);
return super.onCreateOptionsMenu(menu);
}
// get note from the intent
private void getNoteFromIntent(){
if (!getIntent().getStringExtra(Statics.KEY_NOTE_ACTIVITY).equals(Statics.NOTE_DEFAULT_UID)){
note = MySharedPreferences.LoadCheckListNoteFromSharedPreferences(getIntent().getStringExtra(Statics.KEY_NOTE_ACTIVITY),getApplicationContext());
} else {
note = new CheckListNote();
}
}
private void changeViewsColor(int color){
// set the global theme
setTheme(StyleManager.getTheme(color));
// set the appropriate layout
setContentView(R.layout.activity_check_list_note);
// change status bar color
getWindow().setStatusBarColor(getResources().getColor(StyleManager.getThemeColor(color)));
// set up FAB action
fab = findViewById(R.id.fab_add_item);
fab.setOnClickListener(view -> onFabClickListener());
// setting the toolbar
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(getResources().getColor(StyleManager.getThemeColor(color)));
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
// setting the note title
titleView = findViewById(R.id.note_title_view);
titleView.setText("");
titleView.setTextColor(getResources().getColor(StyleManager.getThemeColorDark(color)));
titleView.setHintTextColor(getResources().getColor(StyleManager.getThemeColorLight(color)));
// setting the character counter for the note title
titleCharacterCount = findViewById(R.id.note_title_characters);
String m = titleView.getText().toString().trim().length()+ getString(R.string.text_divider)+ getResources().getInteger(R.integer.title_max_length);
titleCharacterCount.setText(m);
titleCharacterCount.setTextColor(getResources().getColor(StyleManager.getThemeColor(color)));
titleView.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int aft)
{
}
#Override
public void afterTextChanged(Editable s)
{
// this will show characters remaining
String msg = titleView.getText().toString().length()+ getString(R.string.text_divider)+ getResources().getInteger(R.integer.title_max_length);
titleCharacterCount.setText(msg);
}
});
// setting the color view
colorView = findViewById(R.id.note_color_view);
colorView.setOnClickListener(view -> buildColorPickDialog());
colorView.setBackgroundResource(StyleManager.getBackground(color));
adapter = new CheckListAdapter(getApplicationContext(),note.getContent(),color);
adapter.setOnItemClickListener(new CheckListAdapter.OnItemClickListener() {
#Override
public void onChecked(int position) {
Toast.makeText(CheckListNoteActivity.this, "Checked item: " +position, Toast.LENGTH_SHORT).show();
}
#Override
public void onUnchecked(int position) {
Toast.makeText(CheckListNoteActivity.this, "Unchecked item: " +position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSetPriority(int position) {
}
#Override
public void onSetReminder(int position) {
}
#Override
public void onDelete(int position) {
adapter.removeItem(position);
Toast.makeText(CheckListNoteActivity.this, "List has "+note.getContent().size()+" elements", Toast.LENGTH_SHORT).show();
}
});
contentView = findViewById(R.id.note_content_view);
contentView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
contentView.setAdapter(adapter);
}
private void switchColor(int color){
String tempTitle = titleView.getText().toString().trim();
changeViewsColor(color);
titleView.setText(tempTitle);
}
// build the color picker dialog
private void buildColorPickDialog(){
FragmentPickColor fragment = new FragmentPickColor(new ColorAdapter(),5,note.getColor());
fragment.show(getSupportFragmentManager(),Statics.TAG_FRAGMENT_COLOR_PICK);
fragment.setOnItemClickListener(new ColorAdapter.OnItemClickListener() {
#Override
public void OnClickListener(int position) {
note.setColor(position);
switchColor(position);
fragment.dismiss();
}
#Override
public void OnLongClickListener(int position) {
}
});
}
private void onFabClickListener(){
FragmentAddCheckListItem fragment = new FragmentAddCheckListItem(note.getColor());
fragment.show(getSupportFragmentManager(),Statics.TAG_FRAGMENT_ADD_CHECK_LIST_ITEM);
fragment.setOnClickListener(new FragmentAddCheckListItem.OnClickListener() {
#Override
public void onConfirmClickListener() {
fragment.getItem().setDescription(fragment.getInputText());
adapter.addItem(fragment.getItem(),0);
fragment.dismiss();
}
#Override
public void onSetPriorityClickListener() {
}
#Override
public void onSetDueTimeClickListener() {
FragmentDatePicker datePicker = new FragmentDatePicker();
datePicker.show(getSupportFragmentManager(),Statics.TAG_FRAGMENT_DATE_PICKER);
datePicker.setOnDateSet((year, month, day) -> {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,year);
c.set(Calendar.MONTH,month);
c.set(Calendar.DAY_OF_MONTH,day);
fragment.getItem().setDueDate(c.getTime().getTime());
fragment.setDueTimeText(DateFormat.getDateInstance().format(new Date(fragment.getItem().getDueDate())));
});
}
});
}
}
Adapter
package com.example.colornoteplus;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
public class CheckListAdapter extends RecyclerView.Adapter<CheckListAdapter.MyViewHolder> {
public CheckListAdapter(Context context,ArrayList<CheckListItem> list, int color) {
this.list = list;
this.color = color;
this.context = context;
}
final private ArrayList<CheckListItem> list;
final private int color;
final private Context context;
private OnItemClickListener listener;
#NonNull
#Override
public CheckListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new CheckListAdapter.MyViewHolder(LayoutInflater.
from(parent.getContext()).
inflate(R.layout.item_check_list,parent,false));
}
#Override
public void onBindViewHolder(#NonNull CheckListAdapter.MyViewHolder holder, int position) {
CheckListItem currentItem = list.get(position);
holder.background.setBackgroundResource(StyleManager.getBackgroundLight(color));
holder.checkBox.setOnCheckedChangeListener((compoundButton, b) -> {
if (b) listener.onChecked(position);
else listener.onUnchecked(position);
});
holder.title.setTextColor(context.getResources().getColor(StyleManager.getThemeColorDark(color)));
holder.title.setHintTextColor(context.getResources().getColor(StyleManager.getThemeColor(color)));
assert currentItem != null;
holder.title.setText(currentItem.getDescription().trim());
holder.dueTimeText.setTextColor(context.getResources().getColor(StyleManager.getThemeColor(color)));
holder.dueTimeText.setText(currentItem.getDoneDate() != -1 ? DateFormat.getDateInstance().format(new Date(currentItem.getDueDate())) : context.getString(R.string.set_reminder));
holder.dueTimeText.setOnClickListener(view -> listener.onSetReminder(position));
holder.priorityText.setTextColor(context.getResources().getColor(StyleManager.getThemeColor(color)));
holder.priorityText.setText(currentItem.priorityToString(context));
holder.priorityText.setOnClickListener(view -> listener.onSetPriority(position));
holder.delete.setBackgroundResource(StyleManager.getBackground(color));
holder.delete.setOnClickListener(view -> {
// listener.onDelete(position);
removeItem(position);
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
CheckBox checkBox;
ConstraintLayout background;
EditText title;
ImageButton delete;
TextView priorityText,dueTimeText;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.item_check_box);
title = itemView.findViewById(R.id.item_title);
dueTimeText = itemView.findViewById(R.id.item_due_time_text);
priorityText = itemView.findViewById(R.id.item_priority_text);
delete = itemView.findViewById(R.id.item_delete);
background = itemView.findViewById(R.id.item_background);
}
}
public void addItem(CheckListItem item,int position){
if (position < 0){
list.add(item);
notifyItemInserted(list.size()-1);
}
else {
list.add(position,item);
notifyItemInserted(position);
}
}
public void removeItem(int position){
list.remove(position);
notifyItemRemoved(position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
public interface OnItemClickListener{
void onChecked(int position);
void onUnchecked(int position);
void onSetPriority(int position);
void onSetReminder(int position);
void onDelete(int position);
}
}
public void addItem(CheckListItem item, int position) {
if (position >= 0) {
list.add(position, item);
notifyItemInserted(position);
}
}
public void removeItem(int position) {
if (position >= 0) {
list.remove(position);
notifyItemRemoved(position);
}
}
And in onBindViewHolder use holder.getAdapterPosition() instead of position in your listeners like this:
holder.delete.setOnClickListener(view -> {
// listener.onDelete(position);
removeItem(holder.getAdapterPosition());
});

Cant go from one activity to another in Recycler View

Hello Every One I am trying to move from one activity to another using intent in adaptor class of recycler view but I am getting son=me errors in doing so, Following are the errors:
1.PakistaniActivity is not a Enclosing class.
2.Cannot resolve method StatrActivity();
Here is my code:
PakistaniActivity.Java
package com.recycler.hp.navigationbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class PakistaniActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pakistani);
RecyclerView rl=findViewById(R.id.list);
rl.setLayoutManager(new LinearLayoutManager(this));
String[] languges={"Badnamiyan", "song2","song3","song4","Song5","song6","song7","song8","song9"};
rl.setAdapter(new Adaptor(languges));
}
}
Adaptor.java
package com.recycler.hp.navigationbar;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.URL;
public class Adaptor extends RecyclerView.Adapter<Adaptor.viewholder> {
private String[] data;
public Adaptor(String[] data) {
this.data = data;
}
#Override
public viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_item1, parent, false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(viewholder holder, final int position) {
String title = data[position];
holder.t.setText(title);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long x;
x=getItemId(position);
if(x==0)
{
Intent intent=new Intent(PakistaniActivity.this,Revival_Activity.class);
startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return data.length;
}
public class viewholder extends RecyclerView.ViewHolder {
ImageView i;
TextView t;
public viewholder(View itemView) {
super(itemView);
i = itemView.findViewById(R.id.img1);
t = itemView.findViewById(R.id.main1);
}
}
}
Try not starting activities inside the adapter. You can use this adapter:
public abstract class ClickableAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
private ClickItemListener clickItemListener;
public void setClickItemListener(ClickItemListener clickItemListener) {
this.clickItemListener = clickItemListener;
}
#Override
public void onBindViewHolder(#NonNull final VH holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clickItemListener != null)
clickItemListener.onClickItem(holder.itemView, holder.getAdapterPosition());
else
throw new IllegalStateException("Click listener not set");
}
});
}
public interface ClickItemListener {
void onClickItem(View v, int position);
}
}
Then make your adapter extend mine:
public class Adaptor extends ClickableAdapter<Adaptor.viewholder> {
private String[] data;
public Adaptor(String[] data) {
this.data = data;
}
#Override
public viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_item1, parent, false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(viewholder holder, final int position) {
super.onBindViewHolder(holder,position);
String title = data[position];
holder.t.setText(title);
}
#Override
public int getItemCount() {
return data.length;
}
public class viewholder extends RecyclerView.ViewHolder {
ImageView i;
TextView t;
public viewholder(View itemView) {
super(itemView);
i = itemView.findViewById(R.id.img1);
t = itemView.findViewById(R.id.main1);
}
}
}
Finally in your activity you can set the behaviour for the adapter:
Adaptor adapter = new Adaptor(languges)
rl.setAdapter(adapter);
adapter.setClickItemListener(new ClickableAdapter.ClickItemListener() {
#Override
public void onClickItem(View v, int position) {
if(position==0)
{
Intent intent=new Intent(PakistaniActivity.this,Revival_Activity.class);
startActivity(intent);
}
}
});
Write
Intent intent=new Intent(getContext(),Revival_Activity.class);
startActivity(intent);
instead of this
Intent intent=new Intent(PakistaniActivity.this,Revival_Activity.class);
startActivity(intent);
or
pass the context from the from PakistaniActivity to the Adapter class and user the context as the data member of the adapter class
Pass the context of PakistaniActivity into Adapter
new Adaptor(languges,getApplicationContext);
private Context context;
public Adaptor(String[] data,Conetext context) {
this.data = data;
this.context = conetext;
}
Intent intent=new Intent(context,Revival_Activity.class);
startActivity(intent);
Try using this:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
long x;
x=getItemId(position);
if(x==0){
Intent intent = new Intent(getContext(), Revival_Activity.class);
context.startActivity(intent);

How can i get the 3 textview from recyclerview and pass it to dialogbox

Im new to android programming so can you provide me the right code.
this is my code. the data is from sqlite. my problem is . How can i get the 3 textview from recyclerview and pass it to dialogbox when clicked? i finally made dialogbox but i can get only the position of the item i want to get all of the three textview data. please help me.
FragmentMeal.java
package inncharge.poy.madrigal.innchargev1.fragments;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.database.DatabaseHelper;
import inncharge.poy.madrigal.innchargev1.adapters.VivzAdapter;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentMeal#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentMeal extends Fragment {
private DatabaseHelper db;
private RecyclerView recyclerView;
private VivzAdapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentMeal.
*/
// TODO: Rename and change types and number of parameters
public static FragmentMeal newInstance(String param1, String param2) {
FragmentMeal fragment = new FragmentMeal();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentMeal() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
db = new DatabaseHelper(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_meal, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.mealList);
adapter = new VivzAdapter(getActivity(),db.getMealData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int postion) {
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.custom_dialog);
dialog.show();
final EditText editText = (EditText)dialog.findViewById(R.id.editText_pin);
Button submitButton = (Button)dialog.findViewById(R.id.submit_button);
Button cancelButton = (Button)dialog.findViewById(R.id.cancel_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText.getText().toString();
Toast.makeText(getActivity(), "Pin submitted is : " + text, Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(getActivity(), "onLongClick" + position, Toast.LENGTH_SHORT).show();
}
}));
return view;
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
Log.d("VIVZ", "constructor invoked ");
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d("VIVZ","onSingleTapUp " + e);
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null){
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
Log.d("VIVZ", "onLongPress " + e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)){
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
Log.d("VIVZ","onTouchEvent "+ e);
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener {
public void onClick(View arg1, int arg2);
public void onLongClick(View view, int position);
}
}
VivzAdapter.java
package inncharge.poy.madrigal.innchargev1.adapters;
import android.content.ClipData;
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.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.fragments.FragmentMeal;
import inncharge.poy.madrigal.innchargev1.pojo.Contact;
import inncharge.poy.madrigal.innchargev1.pojo.Information;
/**
* Created by Madrigal on 7/18/2015.
*/
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder> {
private Context context;
private final LayoutInflater inflater;
List<Contact> data = Collections.emptyList();
public VivzAdapter(Context context, List<Contact> data){
this.context=context;
inflater = LayoutInflater.from(context);
this.data=data;
}
public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
Log.d("VIVZ","onCreateHolder called ");
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Contact current = data.get(position);
Log.d("VIVZ", "onBindViewHolder called " + position);
holder.itemId.setText(String.valueOf(current.getId()));
holder.title.setText(current.getName());
holder.email.setText(current.getEmail());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public TextView email;
public TextView itemId;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listTextName);
email = (TextView) itemView.findViewById(R.id.listTextUname);
itemId = (TextView) itemView.findViewById(R.id.listTextId);
}
#Override
public void onClick(View v) {
}
}
}
Slidenerd makes some great videos, he helped me a lot as well when I started.
You might want to reconsider what you're trying to do and approach it differently... Why would you want to pass 3 textview from your UI into a dialog?
This is going to be painful.
Seems like you're going to have to extend DialogFragment (i'm assuming that's what you're using for a dialog, maybe an alert?). Create a static factory method inside the DialogFragment like this...
public class MyDialog extends DialogFragment {
private static tv1, tv2, tv3;
public static MyDialog newInstance(TextView tv1, TextView tv2, TextView tv3){
MyDialog.tv1 = tv1;
MyDialog.tv2 = tv2;
MyDialog.tv3 = tv3;
return new MyDialog();
}
}
Once you have this complete, create this dialog fragment inside that onClick method in the ViewHolder class. Instantiate the DialogFragment by doing this...
MyDialog.newInstance(title,email,itemId).show(getFragmentManager(),"dialog_tag");
Like i said before, it's seems sloppy and is probably error prone. There may be a better way of doing this but this is all I can think of off the top of my head. Let me know how it works out for you.. or perhaps revise your question so we can better help you reach a better solution to what you're trying to do.

Categories

Resources