I have a list of clients that I show in a reciclerView
custom, that list has some Editext
of which I need to obtain the value, I found some examples but they don't work for me:
for (int i = 0; i < mAdapter.getItemCount(); i++)
{
RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForItemId(i);
EditText text = holder.itemView.findViewById(R.id.title_card);
String text = textView.getText().toString();
}
It throws me the following error:
java.lang.NullPointerException: Attempt to read from field 'android.view.View androidx.recyclerview.widget.RecyclerView$ViewHolder.itemView' on a null object
I know that recyclerView is not null since it is showing a list on the screen
if i do this:
for (int i = 0; i <data ; i++) {
View view = mRecyclerView.getRootView();
Log.i("layout",view.toString());
TextView name = view.findViewById(R.id.title_card);
String nm = name.getText().toString().trim();
Log.i("nombre",nm);
}
It only brings me the first name on the list 5 times
My adapter class:
public class ClienteAdapter extends RecyclerView.Adapter<ClienteAdapter.ViewHolder> {
private Context mContext;
private List<Cliente> mClienteList;
private SharedPreferences sharedPrefs;
private LocationManager mLocationManager;
/**
* Constructs a new {@link ClienteAdapter}
*
* @param context of the app
* @param ClienteList is the list of Cliente, which is the data source of the adapter
*/
public ClienteAdapter(Context context, List<Cliente> ClienteList) {
mContext = context;
mClienteList = ClienteList;
}
@Override
public ClienteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cliente_card_item, parent, false);
return new ViewHolder(v);
}
@Override
public int getItemCount() {
return mClienteList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView titleTextView;
private TextView sectionTextView;
private TextView authorTextView;
private TextView dateTextView;
private ImageView shareImageView;
private ImageView btnPedido;
private ImageView btnCheckin;
private TextView trailTextView;
private CardView cardView;
ViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.title_card);
sectionTextView = itemView.findViewById(R.id.section_card);
authorTextView = itemView.findViewById(R.id.author_card);
dateTextView = itemView.findViewById(R.id.date_card);
shareImageView = itemView.findViewById(R.id.btnMaps);
btnCheckin = itemView.findViewById(R.id.btnCheckin);
btnPedido = itemView.findViewById(R.id.btnPedido);
trailTextView = itemView.findViewById(R.id.trail_text_card);
cardView = itemView.findViewById(R.id.card_view);
}
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
// Change the color theme of Title TextView by using the user's stored preferences
// Change text size of TextView by using the user's stored preferences
setTextSize(holder);
// Find the current Cliente that was clicked on
final Cliente currentCliente = mClienteList.get(position);
holder.titleTextView.setText(currentCliente.getNombre());
holder.sectionTextView.setText(currentCliente.getRazonSocial());
// If the author does not exist, hide the authorTextView
if (currentCliente.getNombre() == null) {
holder.authorTextView.setVisibility(View.GONE);
} else {
holder.authorTextView.setVisibility(View.VISIBLE);
holder.authorTextView.setText(currentCliente.getDepartamento()+" - "+currentCliente.getMunicipio());
}
// Get time difference between the current date and web publication date and
// set the time difference on the textView
holder.dateTextView.setText(formatDate(currentCliente.getFechaHoraCreacion()));
// Get string of the trailTextHTML and convert Html text to plain text
// and set the plain text on the textView
holder.trailTextView.setText(currentCliente.getDireccion());
if (currentCliente.getLatitud()>0){
holder.shareImageView.setColorFilter(Color.GREEN);
}
// Set an OnClickListener to open a website with more information about the selected article
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getApplicationContext(), ClienteActivity.class);
intent.putExtra("cliente",currentCliente);
mContext.startActivity(intent);
}
});
// Set an OnClickListener to share the data with friends via email or social networking
holder.shareImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
holder.btnPedido.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int idCliente = currentCliente.getId();
Intent intent = new Intent(mContext.getApplicationContext(), OrdenActivity.class);
intent.putExtra("cliente",currentCliente);
mContext.startActivity(intent);
}
});
holder.btnCheckin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext.getApplicationContext(), CheckinActivity.class);
intent.putExtra("cliente",currentCliente);
mContext.startActivity(intent);
}
});
}
/**
* Set the user preferred color theme
*/
/**
* Set the text size to the text size the user choose.
*/
private void setTextSize(ViewHolder holder) {
// Get the text size string from SharedPreferences and check for the value associated with the key
String textSize = sharedPrefs.getString(
mContext.getString(R.string.settings_text_size_key),
mContext.getString(R.string.settings_text_size_default));
// Change text size of TextView by using the user's stored preferences
if (textSize.equals(mContext.getString(R.string.settings_text_size_medium_value))) {
holder.titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp22));
holder.sectionTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp14));
holder.trailTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp16));
holder.authorTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp14));
holder.dateTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp14));
} else if (textSize.equals(mContext.getString(R.string.settings_text_size_small_value))) {
holder.titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp20));
holder.sectionTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp12));
holder.trailTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp14));
holder.authorTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp12));
holder.dateTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp12));
} else if (textSize.equals(mContext.getString(R.string.settings_text_size_large_value))) {
holder.titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp24));
holder.sectionTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp16));
holder.trailTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp18));
holder.authorTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp16));
holder.dateTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
mContext.getResources().getDimension(R.dimen.sp16));
}
}
/**
* Clear all data (a list of {@link Cliente} objects)
*/
public void clearAll() {
mClienteList.clear();
notifyDataSetChanged();
}
/**
* Add a list of {@link Cliente}
*
* @param ClienteList is the list of Cliente, which is the data source of the adapter
*/
public void addAll(List<Cliente> ClienteList) {
mClienteList.clear();
mClienteList.addAll(ClienteList);
notifyDataSetChanged();
}
/**
* Convert date and time in UTC (webPublicationDate) into a more readable representation
* in Local time
*
* @param dateStringUTC is the web publication date of the article (i.e. 2014-02-04T08:00:00Z)
* @return the formatted date string in Local time(i.e "Jan 1, 2000 2:15 AM")
* from a date and time in UTC
*/
private String formatDate(String dateStringUTC) {
// Parse the dateString into a Date object
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
Date dateObject = null;
try {
dateObject = simpleDateFormat.parse(dateStringUTC);
} catch (ParseException e) {
e.printStackTrace();
}
// Initialize a SimpleDateFormat instance and configure it to provide a more readable
// representation according to the given format, but still in UTC
SimpleDateFormat df = new SimpleDateFormat("MMM d, yyyy h:mm a");
String formattedDateUTC = df.format(dateObject);
// Convert UTC into Local time
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = df.parse(formattedDateUTC);
df.setTimeZone(TimeZone.getDefault());
} catch (ParseException e) {
e.printStackTrace();
}
return df.format(date);
}
/**
* Get the formatted web publication date string in milliseconds
*
* @param formattedDate the formatted web publication date string
* @return the formatted web publication date in milliseconds
*/
private static long getDateInMillis(String formattedDate) {
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("MMM d, yyyy h:mm a");
long dateInMillis;
Date dateObject;
try {
dateObject = simpleDateFormat.parse(formattedDate);
dateInMillis = dateObject.getTime();
return dateInMillis;
} catch (ParseException e) {
Log.e("Problem parsing date", e.getMessage());
e.printStackTrace();
}
return 0;
}
You are trying to get the values that are added to the
RecyclerView
, in the first case you get the error:this is because you don't actually have all the views created in your RecyclerView, remember that precisely this avoids having views in memory unnecessarily, in fact if the view leaves the screen, it is deleted, and when it enters the screen it is created or deleted. recycle again.
For this reason when trying to reference an element that doesn't exist you get a
NullPointerException
.In the second case, you comment that you only get the first name of the list 5 times, this is because you are actually referencing the same view.
In regards to your question:
how to iterate or get the values of a RecyclerView in android?
In this case, the best approach is to obtain the values directly from the objects that add the values to the views generated by
RecyclerView
it in your Adapter and not from the views created, since some of these elements may not exist as they are not visible on the screen.Create objects to fill your Adapter and from here get the properties of each element in the list.
I was finally able to answer my question, by doing the following:
reciclerView
is created at run time (when you scroll) therefore it is not possible to go through it and obtain all the values that are going to be displayed since they only exist until they are displayed on the screenhere I leave my adapter class:
}