Android: How to setTag with Adapter - java

I have following situation: I have PostBaseAdapter where I initialize my views and MainActivity where I want to set Checkbox with switch parameter by getTag() but I don't know how to setTag() for my checkbox and where.
public class PostBaseAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ArrayList<PostValue> postValueArrayList;
public PostBaseAdapter(Context context, ArrayList<PostValue> postValueArrayList) {
this.layoutInflater = LayoutInflater.from(context);
this.postValueArrayList = postValueArrayList;
}
#Override
public int getCount() {
return postValueArrayList.size();
}
#Override
public PostValue getItem(int position) {
return postValueArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_post, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
PostValue postValue = getItem(position);
viewHolder.tvTitle.setText(postValue.getBrand());
viewHolder.tvPublishDate.setText(postValue.getDate());
viewHolder.cost.setText(postValue.getPrice());
viewHolder.descriptionOfItem.setText(postValue.getDescription());
viewHolder.deliveryTime.setText("Cрок доставки: "+postValue.getDeliveryTime()+" дней");
viewHolder.checkBox.setChecked(false);
return convertView;
}
private class ViewHolder {
Button order;
CheckBox checkBox;
TextView tvTitle, tvPublishDate, cost, deliveryTime, descriptionOfItem;
public ViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
tvPublishDate = (TextView) item.findViewById(R.id.tvPublishDate);
cost = (TextView) item.findViewById(R.id.cost);
deliveryTime = (TextView) item.findViewById(R.id.delivery_time);
descriptionOfItem = (TextView) item.findViewById(R.id.description);
checkBox = (CheckBox) item.findViewById(R.id.checkbox);
order = (Button) item.findViewById(R.id.order);
}
}
}
and MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
order = (Button) findViewById(R.id.order);
checkbox = (CheckBox) findViewById(R.id.checkbox);
lvPcsPost = (ListView) findViewById(R.id.lvPcsPost);
lvPcsPost.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvPcsPost.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (postValueArrayList != null && postValueArrayList.size() > 0) {
}
}
});
new PostAsync().execute();
//Установка Статус Бара определенного цвета
Window window = this.getWindow();
window.setStatusBarColor(this.
getResources().getColor(R.color.colorPrimary));
Paper.init(this);
}
class PostAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "Загрузка", "Ждите, идет загрузка автозапчастей ...", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get(getIntent().getStringExtra("level")); // Передаем Интент с артикулом из поиска
postValueArrayList = helper.getPostsList();
return null;
}
#Override
protected void onPostExecute(Void result) {
PostBaseAdapter postBaseAdapter = new PostBaseAdapter(MainActivity.this, postValueArrayList);
lvPcsPost.setAdapter(postBaseAdapter);
pd.dismiss();
}
}
public void checkBoxClick(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getTag().toString()) {
case "0":
if (checked) {
Toast.makeText(this, "ЩЕЛК:", Toast.LENGTH_LONG).show();
}
break;
}
}

Related

How do I send the text of the ListView item that was clicked to my new activity?

I would like someone to click on an item in my ListView and then my new activity would start and the text of the item they clicked on should be set as the text of the TextView in my new activity. Currently with the following code, my TextView result is:
'com.example.draft.AnimalNames#31571cf'
Here is what I have in MainActivity.java:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedName = (list.getItemAtPosition(position).toString());
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("clickedName", clickedName);
startActivity(intent);
System.out.println(clickedName);
}
});
And in my new activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
Intent intent = getIntent();
String clickedName = intent.getStringExtra("clickedName");
animalName = findViewById(R.id.textView);
animalName.setText(clickedName);
}
And in my AnimalNames.java file:
public class AnimalNames {
private String animalName;
public AnimalNames(String animalName) {
this.animalName = animalName;
}
public String getanimalName() {
return this.animalName;
}
}
I don't think it's relevant to my question but here is my ListViewAdapter.java file:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList; // Declare a null variable
private ArrayList<AnimalNames> arraylist; // Declare a null array
public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
mContext = context;
this.animalNamesList = animalNamesList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AnimalNames>();
this.arraylist.addAll(animalNamesList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public AnimalNames getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_view_items, null); // Locate the TextViews in list_view_items.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(animalNamesList.get(position).getanimalName());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (AnimalNames wp : arraylist) {
if (wp.getanimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
String clickedName = (list.getItemAtPosition(position).toString());
By calling toString() method, it will give you the object reference, which is what you get in the TextView.
According to your code, if you wish to see the Animal name, you should do (and fix the method name to getAnimalName):
String clickedName = ((AnimalNames)list.getItemAtPosition(position)).getanimalName();
getItemAtPosition() returns an Object, so you need to cast it to the correct class.

cant Get Original Index from Filtered list view

I have a listview and an editText to filter data. It filters data correctly but e.g, if I filter list and open filtered item it shows me the data of item which was at index 0 of original list not that of filtered item.
My Adapter class:
public class Patient_Adapter extends BaseAdapter implements Filterable{
Activity context;
String[] name, age, number, dip_rate;
//for filtering use arraylists
LayoutInflater inflater;
private ValueFilter valueFilter;
ArrayList<ArrayList_get_set> arrayList;
private ArrayList<ArrayList_get_set> StringFilterList;
public Patient_Adapter(Activity applicationContext, ArrayList<ArrayList_get_set> arrayList) {
this.context = applicationContext;
/////
this.arrayList = arrayList;
StringFilterList = arrayList;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getFilter();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int i) {
return arrayList.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
private class Viewholder{
TextView name_
,date_
,number_
,dip_rate_
,tv_request_number;
Button button;
}
#Override
public View getView(final int position, View view, final ViewGroup viewGroup) {
Viewholder viewholder;
LayoutInflater inflater = context.getLayoutInflater();
if (view == null){
viewholder = new Viewholder();
view = inflater.inflate(R.layout.patient_item_list,null);
viewholder.tv_request_number = (TextView) view.findViewById(R.id.s_req_num);
viewholder.name_ = (TextView) view.findViewById(R.id.name);
viewholder.button = (Button) view.findViewById(R.id.btn_re);
viewholder.date_ = (TextView) view.findViewById(R.id.date);
view.setTag(viewholder);
}
else {
viewholder = (Viewholder) view.getTag();
}
viewholder.tv_request_number.setText((arrayList.size()-position)+".");
viewholder.name_.setText(arrayList.get(position).getName());
viewholder.date_.setText(getDate(Long.parseLong(arrayList.get(position).getDate())));
viewholder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ListView)viewGroup).performItemClick(v,position,1);
}
});
return view;
}
//Filter Results
#Override
public Filter getFilter() {
if(valueFilter==null) {
valueFilter=new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if(constraint != null && constraint.length()>0){
ArrayList<ArrayList_get_set> filterList = new ArrayList<>();
for(int i=0;i<StringFilterList.size();i++){
if((StringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ArrayList_get_set contacts = new ArrayList_get_set();
contacts.setName(StringFilterList.get(i).getName());
contacts.setDate(StringFilterList.get(i).getDate());
filterList.add(contacts);
}
}
results.count=filterList.size();
results.values=filterList;
}else{
results.count=StringFilterList.size();
results.values=StringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
arrayList = (ArrayList<ArrayList_get_set>) results.values;
notifyDataSetChanged();
}
}
This my main activity code
simListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id == 1){
//CUSTOM DIALOG///////////////////////////////
final Dialog dialog = new Dialog(getActivity());
dialog.setCanceledOnTouchOutside(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_re_evaluate);
name_ = (TextView) dialog.findViewById(R.id.name);
f_name_ = (TextView) dialog.findViewById(R.id.f_name);
age_ = (TextView) dialog.findViewById(R.id.age);
number_ = (TextView) dialog.findViewById(R.id.number);
gender_ = (TextView) dialog.findViewById(R.id.gender);
dip_rate_ = (TextView) dialog.findViewById(R.id.dip_rate);
date_ = (TextView) dialog.findViewById(R.id.date);
name_.setText(name[position]);
f_name_.setText(f_name[position]);
age_.setText(age[position]);
number_.setText(number[position]);
dip_rate_.setText(dip_rate[position]);
gender_.setText(gender[position]);
date_.setText(getDate(Long.parseLong(date[position])));
Button re_eval = (Button) dialog.findViewById(R.id.btn);
Button btn_cross = (Button) dialog.findViewById(R.id.cross);
btn_cross.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
re_eval.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p_name = name_.getText().toString();
p_f_name = f_name_.getText().toString();
p_age = age_.getText().toString();
p_number = number_.getText().toString();
p_dip_rate = dip_rate_.getText().toString();
p_gender = gender_.getText().toString();
p_date = date_.getText().toString();
//go from one fragment to another
Fragment fragment = null;
//send data to next fragment
Bundle bundle = new Bundle();
bundle.putString("name", p_name);
bundle.putString("f_name", p_f_name);
bundle.putString("age", p_age);
bundle.putString("number", p_number);
bundle.putString("dip_rate", p_dip_rate);
bundle.putString("gender", p_gender);
bundle.putString("date", p_date);
fragment = new Questions();
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment.setArguments(bundle);
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
dialog.dismiss();
}
});
dialog.show();
}
}
});
performing filtering here
protected void onPostExecute(String s) {
progressDialog.dismiss();
if (server_check) {
if (server_response.equals("1")) {
if (name.length > 0) {
patient_adapter = new Patient_Adapter(getActivity(),
arrayList);
simListView.setAdapter(patient_adapter);
//filtering data
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
patient_adapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});

RecyclerView on item click NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So I've set up my RecyclerView with SQLite DB and it's populating the list, but every time I click on the list item it should open the new activity and pass data to it via intent extras.
The click gives me NullPointerException:
Process: com.daroioradecic.fxtodo, PID: 6762
java.lang.NullPointerException: Attempt to invoke interface method 'void data.RecAdapter$ItemClickCallback.onItemClick(int)' on a null object reference
at data.RecAdapter$RecHolder.onClick(RecAdapter.java:106)
at android.view.View.performClick(View.java:4856)
at android.view.View$PerformClick.run(View.java:19956)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
in my Recycler View adapter class which is:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecHolder> {
private int previousPosition = 0;
private List<Todo> listData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecAdapter(List<Todo> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public RecHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_row_za_listu, parent, false);
return new RecHolder(view);
}
#Override
public void onBindViewHolder(RecHolder holder, int position) {
Todo item = listData.get(position);
holder.title.setText(item.getTitle());
if (position > previousPosition) {
AnimationUtil.animate(holder, true);
} else {
AnimationUtil.animate(holder, false);
}
previousPosition = position;
}
#Override
public int getItemCount() {
return listData.size();
}
public void setListData(ArrayList<Todo> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
class RecHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView title;
private View container;
public RecHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tekstNaListi);
container = itemView.findViewById(R.id.cont_item_root);
container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickCallback.onItemClick(getAdapterPosition());
}
}
}
It gives the error on line itemClickCallback.onItemClick(getAdapterPosition()); which is the last line in the class.
I'm overriding onClick in the class where recycler view is populated like this:
#Override
public void onItemClick(int p) {
Todo item = (Todo) listData.get(p);
Intent i = new Intent(HomeScreen.this, Details.class);
Bundle extras = new Bundle();
extras.putString("naslov", item.getTitle());
extras.putString("datum", item.getRecordDate());
extras.putInt("id", item.getItemId());
startActivity(i);
}
That class implements implements RecAdapter.ItemClickCallback
Any ideas? Thanks!
MAIN ACTIVITY CLASS: (keep in mind that I just transitioned from ListView so I haven't done any cleaning)
public class HomeScreen extends AppCompatActivity implements RecAdapter.ItemClickCallback {
private RecyclerViewUtils.ShowHideToolbarOnScrollingListener showHideToolbarListener;
//SCROLL
private Toolbar tToolbar;
// REC
private RecyclerView recView;
private RecAdapter adapter;
private ArrayList listData;
// ZA SNACKBAR
private CoordinatorLayout coordinatorLayout;
private RelativeLayout relLay;
// NAVIGACIJA
private DrawerLayout mDrawer;
private ActionBarDrawerToggle drawerToggle;
private Toolbar toolbar;
NavigationView nvDrawer;
DrawerLayout dlDrawer;
//----------------------------------------------------------------------------------------------
DatabaseHandler dba;
private ArrayList<Todo> dbTodo = new ArrayList<>();
private TodoAdapter todoAdapter;
private ListView lista;
private Cursor mCursor;
LinearLayout layoutZaUnosTodoa;
EditText editTextZaNazivTodoa;
Button buttonSave;
private CheckBox checkBoxDoneOrNotNaListi;
android.support.design.widget.FloatingActionButton fab;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.activity_home_screen);
tToolbar = (Toolbar) findViewById(R.id.tToolbar);
setSupportActionBar(tToolbar);
tToolbar.setNavigationIcon(R.drawable.ic_nav_menu);
getSupportActionBar().setTitle(R.string.app_name);
// REC
recView = (RecyclerView) findViewById(R.id.rec_list);
recView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RecAdapter(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
recView.addOnScrollListener(showHideToolbarListener = new RecyclerViewUtils.ShowHideToolbarOnScrollingListener(tToolbar));
if (savedInstanceState != null) {
showHideToolbarListener.onRestoreInstanceState((RecyclerViewUtils.ShowHideToolbarOnScrollingListener.State) savedInstanceState
.getParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE));
}
layoutZaUnosTodoa = (LinearLayout) findViewById(R.id.layoutZaUnosTodoa);
editTextZaNazivTodoa = (EditText) findViewById(R.id.editTextZaNazivTodoa);
editTextZaNazivTodoa.setSelection(editTextZaNazivTodoa.getText().length());
buttonSave = (Button) findViewById(R.id.buttonSave);
//lista = (ListView) findViewById(R.id.lista);
fab = (android.support.design.widget.FloatingActionButton) findViewById(R.id.fab);
checkBoxDoneOrNotNaListi = (CheckBox) findViewById(R.id.checkBoxDoneOrNotNaListi);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordiantorLayout);
relLay = (RelativeLayout) findViewById(R.id.relLay);
refreshData();
layoutZaUnosTodoa.setVisibility(View.GONE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutZaUnosTodoa.setVisibility(View.VISIBLE);
}
});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveToDB();
layoutZaUnosTodoa.setVisibility(View.GONE);
}
});
relLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutZaUnosTodoa.setVisibility(View.GONE);
}
});
dlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
dlDrawer.setDrawerListener((DrawerLayout.DrawerListener) drawerToggle);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
drawerToggle.syncState();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(RecyclerViewUtils.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE,
showHideToolbarListener.onSaveInstanceState());
super.onSaveInstanceState(outState);
}
private void saveToDB() {
Todo todo = new Todo();
todo.setTitle(editTextZaNazivTodoa.getText().toString());
dba.addTodo(todo);
adapter.notifyDataSetChanged();
dba.close();
editTextZaNazivTodoa.setText("");
}
public void refreshData() {
dbTodo.clear();
dba = new DatabaseHandler(HomeScreen.this);
ArrayList<Todo> todoFromDB = dba.getTodo();
for (int i = 0; i < todoFromDB.size(); i++) {
String title = todoFromDB.get(i).getTitle();
String dateText = todoFromDB.get(i).getRecordDate();
int mid = todoFromDB.get(i).getItemId();
Todo myTodo = new Todo();
myTodo.setTitle(title);
myTodo.setItemId(mid);
myTodo.setRecordDate(dateText);
dbTodo.add(myTodo);
}
dba.close();
adapter = new RecAdapter(dbTodo, this);
recView.setAdapter(adapter);
// todoAdapter = new TodoAdapter(HomeScreen.this, R.layout.layout_row_za_listu, dbTodo);
//Animation collapseList = AnimationUtils.loadAnimation(HomeScreen.this, R.anim.collapse_search_results);
//lista.startAnimation(collapseList);
//lista.setAdapter(todoAdapter);
// todoAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(int p) {
Todo item = (Todo) listData.get(p);
Intent i = new Intent(HomeScreen.this, Details.class);
Bundle extras = new Bundle();
extras.putString("naslov", item.getTitle());
extras.putString("datum", item.getRecordDate());
extras.putInt("id", item.getItemId());
startActivity(i);
}
/* #Override
public void onSecondaryItemClick(int p) {
}*/
public class TodoAdapter extends ArrayAdapter<Todo> {
Activity activity;
int layoutResource;
Todo todo;
ArrayList<Todo> mData = new ArrayList<>();
public TodoAdapter(Activity act, int resource, ArrayList<Todo> data) {
super(act, resource, data);
activity = act;
layoutResource = resource;
mData = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Todo getItem(int position) {
return mData.get(position);
}
#Override
public int getPosition(Todo item) {
return super.getPosition(item);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null || (row.getTag() == null)) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource, null);
holder = new ViewHolder();
holder.mTitle = (TextView) row.findViewById(R.id.tekstNaListi);
holder.checkBox = (CheckBox) row.findViewById(R.id.checkBoxDoneOrNotNaListi);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.myTodo = getItem(position);
holder.mTitle.setText(holder.myTodo.getTitle());
final ViewHolder finalHolder = holder;
holder.mTitle.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
int mid = finalHolder.myTodo.getItemId();
DatabaseHandler dba = new DatabaseHandler(HomeScreen.this);
dba.deleteTodo(mid);
Snackbar snackbar = Snackbar.make(coordinatorLayout, getResources().getString(R.string.snack_bar_tekst), Snackbar.LENGTH_SHORT);
snackbar.show();
todoAdapter.notifyDataSetChanged();
return true;
}
});
/*holder.mTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = finalHolder.myTodo.getTitle().toString();
String dateText = finalHolder.myTodo.getRecordDate().toString();
int mid = finalHolder.myTodo.getItemId();
Intent i = new Intent(HomeScreen.this, Details.class);
i.putExtra("naslov", title);
i.putExtra("datum", dateText);
i.putExtra("id", mid);
startActivity(i);
}
});*/
final View finalRow = row;
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.mTitle = (TextView) finalRow.findViewById(R.id.tekstNaListi);
if (finalHolder.checkBox.isChecked()) {
finalHolder.mTitle.setPaintFlags(finalHolder.mTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
finalHolder.mTitle.setAlpha(0.5f);
} else if (!finalHolder.checkBox.isChecked()) {
finalHolder.mTitle.setPaintFlags(0);
finalHolder.mTitle.setAlpha(0.8f);
}
}
});
return row;
}
}
class ViewHolder {
Todo myTodo;
TextView mTitle, mContent, mDate;
int mId;
CheckBox checkBox;
}
EDIT:
This error shows up:
java.lang.NullPointerException: Attempt to invoke interface method 'void data.RecAdapter$ItemClickCallback.onItemClick(int)' on a null object reference
at data.RecAdapter$1.onClick(RecAdapter.java:67)
and it refeers to this line in adapter class:
itemClickCallback.onItemClick(position);
1) Check the callback null or not.
#Override
public void onClick(View v) {
if (itemClickCallback!=null){
itemClickCallback.onItemClick(getAdapterPosition());
}
}
2) The activity/class implements the method. This is okay. But, are you set the listener in your onCreate() ?
rectAdapter.setItemClickCallback(this);
3)EDITED Change your adapter like this:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecHolder> {
private int previousPosition = 0;
private List<Todo> listData;
private LayoutInflater inflater;
private ItemClickCallback itemClickCallback;
public interface ItemClickCallback {
void onItemClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecAdapter(List<Todo> listData, Context c) {
this.inflater = LayoutInflater.from(c);
this.listData = listData;
}
#Override
public RecHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.layout_row_za_listu, parent, false);
return new RecHolder(view);
}
#Override
public void onBindViewHolder(RecHolder holder, final int position) {
Todo item = listData.get(position);
holder.title.setText(item.getTitle());
if (position > previousPosition) {
AnimationUtil.animate(holder, true);
} else {
AnimationUtil.animate(holder, false);
}
previousPosition = position;
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemClickCallback.onItemClick(position);
}
});
}
#Override
public int getItemCount() {
return listData.size();
}
public void setListData(ArrayList<Todo> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
class RecHolder extends RecyclerView.ViewHolder {
private TextView title;
private View container;
public RecHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tekstNaListi);
container = itemView.findViewById(R.id.cont_item_root);
}
}}

How to make interface in adapter class

I am making interface in adapter class but it is giving me error that interface expected here.How can I implement interface in adapter class.I made the adapter and main class but showing me error that interface is expected here.
public class Dashboard_Adapter extends ArrayAdapter<Dashboard_Model_File> implements RecyclerSwipeAdapter<Dashboard_Adapter.SimpleViewHolder> {
ArrayList<Dashboard_Model_File> dashboard_model_files_obj;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public Dashboard_Adapter(Context context, int resource, ArrayList<Dashboard_Model_File> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
dashboard_model_files_obj = objects;
}
Typeface font1 = Typeface.createFromAsset(getContext().getAssets(), "fonts/cabin.regular.ttf");
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
TextView textViewPos;
TextView textViewData;
Button buttonDelete;
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(com.daimajia.swipe.R.id.swipe);
textViewPos = (TextView) itemView.findViewById(com.daimajia.swipe.R.id.position);
textViewData = (TextView) itemView.findViewById(com.daimajia.swipe.R.id.text_data);
buttonDelete = (Button) itemView.findViewById(com.daimajia.swipe.R.id.delete);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(getClass().getSimpleName(), "onItemSelected: " + textViewData.getText().toString());
Toast.makeText(view.getContext(), "onItemSelected: " + textViewData.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
public Dashboard_Adapter(Dashboard dashboard, ArrayList<Dashboard_Model_File> dashboard_model_file_arraylist) {
super();
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.title_holder = (TextView) v.findViewById(R.id.title_view);
holder.desc_holder = (TextView) v.findViewById(R.id.desc_view);
holder.url_holder = (TextView) v.findViewById(R.id.url_view);
holder.bookmark_id_holder = (TextView) v.findViewById(R.id.bookmark_id);
holder.alternate_id_holder = (TextView) v.findViewById(R.id.alternate_id);
holder.bookmark_file_holder = (TextView) v.findViewById(R.id.bookmark_file);
holder.mode_holder = (TextView) v.findViewById(R.id.mode_id);
holder.swipeLayout = (SwipeLayout) v.findViewById(com.daimajia.swipe.R.id.swipe);
holder.textViewPos = (TextView) v.findViewById(com.daimajia.swipe.R.id.position);
holder.textViewData = (TextView) v.findViewById(com.daimajia.swipe.R.id.text_data);
holder.buttonDelete = (Button) v.findViewById(com.daimajia.swipe.R.id.delete);
holder.title_holder.setTypeface(font1); holder.title_holder.setTextSize(16.0f);
holder.desc_holder.setTypeface(font1); holder.desc_holder.setTextSize(14.0f);
holder.url_holder.setTypeface(font1); holder.url_holder.setTextSize(10.0f);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageview).execute(dashboard_model_files_obj.get(position).getImage());
holder.title_holder.setText(dashboard_model_files_obj.get(position).getTitle());
holder.desc_holder.setText(dashboard_model_files_obj.get(position).getDescription());
holder.url_holder.setText(dashboard_model_files_obj.get(position).getUrl());
return v;
}
private Context mContext;
private ArrayList<String> mDataset;
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(com.daimajia.swipe.R.layout.recyclerview_item, parent, false);
return view;
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder,final int position) {
String item = mDataset.get(position);
viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
viewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
YoYo.with(Techniques.Tada).duration(500).delay(100).playOn(layout.findViewById(com.daimajia.swipe.R.id.trash));
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick", Toast.LENGTH_SHORT).show();
}
});
viewHolder.buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemManger.removeShownLayouts(viewHolder.swipeLayout);
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataset.size());
mItemManger.closeAllItems();
// Toast.makeText(view.getContext(), "Deleted " + viewHolder.textViewData.getText().toString() + "!", Toast.LENGTH_SHORT).show();
}
});
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(com.daimajia.swipe.R.layout.recyclerview_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public int getItemCount() {
return 0;
}
#Override
public int getSwipeLayoutResourceId(int position) {
return 0;
}
static class ViewHolder {
public ImageView imageview;
public TextView title_holder;
public TextView desc_holder;
public TextView url_holder;
public TextView bookmark_file_holder;
public TextView alternate_id_holder;
public TextView bookmark_id_holder;
public TextView mode_holder;
public TextView txtCategory;
SwipeLayout swipeLayout;
TextView textViewPos;
TextView textViewData;
Button buttonDelete;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
ImageView bmImage;
public DownloadImageTask(ImageView bmImage)
{
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls)
{
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
You are not making an interface, you are trying to implement one. And as per the error it seems like this interface does not exist.

Dynamically adding listitems to baseadapter an android

I want to dynamically add new listitems by pressing a button.but i don't no the right way to do this.
BaseAdapter
public class CompetitionResultListAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<Result> result;
DataManager datamanager;
#Override
public int getCount() {
return result!=null ? result.size() : 0;
}
#Override
public Object getItem(int position) {
return result.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
// inflate the layout
LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(R.layout.list_item_competition_result, parent, false);
}
EditText listItemDate = (EditText) convertView.findViewById(R.id.date);
EditText listItemPlace = (EditText) convertView.findViewById(R.id.place);
EditText listItemComment = (EditText) convertView.findViewById(R.id.comment);
result.get(position).setDate(listItemDate.getText().toString());
result.get(position).setPlace(listItemPlace.getText().toString());
result.get(position).setComment(listItemComment.getText().toString());
return convertView;
}
public void refreshResultList(ArrayList<Result> result){
this.result = result;
notifyDataSetChanged();
}
}
java class
public class AddCompetitionResult extends Fragment {
private CompetitionResultListAdapter competitionResultListAdapter;
private DataManager datamanager;
ArrayList<Result> result;
ListView listView;
private Horse horse;
private Button addResults;
int clickCounter=0;
public AddHorseCompetitionResult(Horse horse) {
this.horse = horse;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_horse_competition_result,
null);
addResults = (Button) view.findViewById(R.id.btn_add_competition_result);
listView = (ListView) view.findViewById(R.id.data_list);
// result = datamanager.create(getActivity());
competitionResultListAdapter = new CompetitionResultListAdapter();
View footerView = ((LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.competition_result_listview_footer, null, false);
listView.addFooterView(footerView);
listView.setAdapter(competitionResultListAdapter);
addResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resultId = null;
// result.add();
competitionResultListAdapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (competitionResultListAdapter.getCount() == position) {
MainActivity mainActivity = MainActivity.getInstance();
mainActivity.setFragment(new AddHorseDetailedInfo(horse),
"Add horse more info");
// datamanager.createResult(result);
} else {
// ContactGroup cg = (ContactGroup)
// competitionResultListAdapter.getItem(position);
// MainActivity mainActivity = MainActivity.getInstance();
// mainActivity.setFragment(new
// ContactListView(cg.getGroupId()), "contacts");
}
}
});
return view;
}
}
// on button CLick
{
// toast a meesaage here : onClick()
result.add(urObject)// simply put create a object of ur result type and put "" values
// finallly call notifyDataSetChanged on adapter
adapter.notifyDataSetChanged();
}
Tryt to replace your adapter code with this.
public class CompetitionResultListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<Result> result;
DataManager datamanager;
#Override
public int getCount() {
return result!=null ? result.size() : 0;
}
#Override
public Object getItem(int position) {
return result.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(activity).inflate(R.layout.list_item_competition_result, null, false);
holder.listItemDate = (EditText) convertView.findViewById(R.id.date);
holder.listItemPlace = (EditText) convertView.findViewById(R.id.place);
holder.listItemComment = (EditText) convertView.findViewById(R.id.comment);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.listItemDate = (EditText) convertView.findViewById(R.id.date);
holder.listItemPlace = (EditText) convertView.findViewById(R.id.place);
holder.listItemComment = (EditText) convertView.findViewById(R.id.comment);
result.get(position).setDate(listItemDate.getText().toString());
result.get(position).setPlace(listItemPlace.getText().toString());
result.get(position).setComment(listItemComment.getText().toString());
return convertView;
}
class ViewHolder {
EditText listItemDate;
EditText listItemPlace;
EditText listItemComment;
}
public void refreshResultList(ArrayList<Result> result){
this.result = result;
notifyDataSetChanged();
}
}

Categories