我有一个我在reciclerView
自定义中显示的客户列表,该列表中有一些Editext
我需要获取值,我找到了一些示例,但它们对我不起作用:
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();
}
它向我抛出以下错误:
java.lang.NullPointerException: Attempt to read from field 'android.view.View androidx.recyclerview.widget.RecyclerView$ViewHolder.itemView' on a null object
我知道 recyclerView 不为空,因为它在屏幕上显示了一个列表
如果我这样做:
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);
}
它只给我带来了 5 次名单上的名字
我的适配器类:
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;
}
您正在尝试获取添加到的值
RecyclerView
,在第一种情况下您会收到错误:这是因为您实际上并没有在 RecyclerView 中创建所有视图,请记住,这正是避免在内存中不必要地拥有视图,事实上,如果视图离开屏幕,它会被删除,当它进入屏幕时它会被创建或删除。再次回收。
因此,当尝试引用不存在的元素时,您会得到一个
NullPointerException
.在第二种情况下,您评论说您只获得列表的名字 5 次,这是因为您实际上引用的是同一个视图。
关于你的问题:
android中如何迭代或者获取一个RecyclerView的值?
在这种情况下,最好的方法是直接从将值添加到
RecyclerView
适配器中由它生成的视图的对象中获取值,而不是从创建的视图中获取值,因为其中一些元素可能不存在,因为它们在屏幕上不可见。创建对象以填充您的适配器,并从此处获取列表中每个元素的属性。
通过执行以下操作,我终于能够回答我的问题:
reciclerView
是在运行时(滚动时)创建的,因此不可能通过它并获取将要显示的所有值,因为它们只存在直到它们显示在屏幕上在这里,我离开了我的适配器类:
}