这是我的适配器代码:
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> implements Filterable{
private ArrayList<AutoData> resultList;
private ItemClickListener itemClickListener;
public DataAdapter(ArrayList<AutoData> resultList) {
this.resultList= resultList;
this.itemClickListener = itemClickListener;
}
@Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_place_card, viewGroup, false);
return new ViewHolder(view, itemClickListener);
}
@Override
public Filter getFilter(){
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults filterResults = new FilterResults();
filterResults.values = resultList;
filterResults.count = resultList.size();
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
}
};
return filter;
}
@SuppressLint("NewApi")
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.tv_name.setText(resultList.get(position).getName());
viewHolder.tv_address.setText(resultList.get(position).getAddress());
}
@Override
public int getItemCount() {
return resultList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView tv_name;
private TextView tv_address;
private EditText editText;
private WeakReference<ItemClickListener> itemClickListenerWeakReference;
public ViewHolder(View view, ItemClickListener itemClickListener) {
super(view);
itemClickListenerWeakReference = new WeakReference<>(itemClickListener);
tv_name = (TextView)view.findViewById(R.id.name_text_view);
tv_address = (TextView)view.findViewById(R.id.address_text_view);
view.setOnClickListener(this);
editText = (EditText) view.findViewById(R.id.location_input);
}
Context mCon;
MainActivity mainActivity;
@Override
public void onClick(View v) {
String string = (String) tv_name.getText();
Toast.makeText(v.getContext(), "ROW PRESSED = " + string, Toast.LENGTH_SHORT).show();
mainActivity.etPlace.setText((string));
}
}
当我运行我的应用程序时,我看到了这个错误:
java.lang.NullPointerException:尝试从字段读取 &#39; android.widget.EditText com.example.user2.trafficmap.MainActivity.etPlace&#39;在null对象上 参考 在com.example.user2.trafficmap.DataAdapter $ ViewHolder.onClick(DataAdapter.java:133)
我该如何解决这个问题?
答案 0 :(得分:2)
更改
mainActivity.etPlace.setText((string));
到
EditText et = (EditText) getWindow().getDecorView().findViewById(R.id.etPlace); //or whatever your ID is
et.setText(your_string);
更新的名称为String
字符串。