How to dissmiss AlertDialog from ArrayAdapter - java

I created singe choice AlertDialog with radio buttons using ArrayAdapter. It's possible to dissmiss that alert dialog when Ratio is selected? I have OnClick listener in ArrayAdapter class holder.name.setOnClickListener, but i have no idea how to to that.
AlertDialog code:
Builder builder = new Builder(serveris, useris, paswordas, BuildBuildingsViewActivity.this, USER_AGENT);
ArrayList<AvailableBuildings> availableBuildings = builder.checkForPossibleBuildings(pastatas.getBuildingLink());
ArrayAdapter<AvailableBuildings> adapter = new AvailableBuildingsAdapter(BuildBuildingsViewActivity.this, R.layout.choice_main, availableBuildings, host, curdid, pastatas.getBuildingLink());
new AlertDialog.Builder(BuildBuildingsViewActivity.this)
.setSingleChoiceItems(adapter, 0, null)
.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
ArrayAdapter code:
public class AvailableBuildingsAdapter extends ArrayAdapter<AvailableBuildings> {
public DBAdapterBuild db_build;
public AvailableBuildingsAdapter(Context context, int textViewResourceId,ArrayList<AvailableBuildings> availableBuildings, String host, String curdid, String aiksteles_link) {
super(context, textViewResourceId, availableBuildings);
this.context = context;
this.availableBuildings = new ArrayList<AvailableBuildings>();
this.availableBuildings.addAll(availableBuildings);
this.host = host;
this.curdid = curdid;
this.aiksteles_link = aiksteles_link;
db_build = new DBAdapterBuild(context, host);
}
private String host;
private Context context;
private String curdid;
private String aiksteles_link;
private ArrayList<AvailableBuildings> availableBuildings;
static class ViewHolder {
RadioButton name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.choice_row, null);
holder = new ViewHolder();
holder.name = (RadioButton) convertView.findViewById(R.id.building_name);
convertView.setTag( holder );
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
db_build.open();
RadioButton name = (RadioButton) v;
AvailableBuildings building = (AvailableBuildings) name.getTag();
Log.e( "Available: ", ""+building.getAvailable_title()+building.getAvailable_code());
Log.e( "Available: ", ""+db_build.insertTitle(1, building.getAvailable_title(), aiksteles_link, curdid, 0, 1, building.getAvailable_type(), "3", building.getAvailable_code()));
db_build.close();
}
});
} else {
// view already defined, retrieve view holder
holder = (ViewHolder) convertView.getTag();
}
AvailableBuildings building = availableBuildings.get(position);
if ( building == null ) {
}
holder.name.setText(building.getAvailable_title());
holder.name.setTag(building);
return convertView;
}
}

I solve this problem passing to ArrayAdapter constructor Dialog object and next doing like this:
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
db_build.open();
RadioButton name = (RadioButton) v;
AvailableBuildings building = (AvailableBuildings) name.getTag();
Log.e( "Available: ", ""+building.getAvailable_title()+building.getAvailable_code());
Log.e( "Available: ", ""+db_build.insertTitle(1, building.getAvailable_title(), aiksteles_link, curdid, 0, 1, building.getAvailable_type(), "3", building.getAvailable_code()));
db_build.close();
dia.dismiss();
}
});

Related

Android: Checkbox in listview (how to create OnCheckedChangeListener in Adapter)

I'm creating a To-do list application and I have a question regarding to using checkboxes and its listeners in List Adapter. My single row in listview contains three TextViews and one Checkbox. I want to change background of single row when user "check" the checkbox. I have read that i should put checkbox listener in my adapter class and so I did it. Now is the problem - when i add few rows to my listview and left the checkbox unchecked for all of them all works fine, but when I add a row, check the checkbox and try to add another one I get error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
Below is code of my adapter. Thank you for any advice. I'm just starting with Android programming so thank you for understanding in advance.
public class ToDoAdapter extends ArrayAdapter<ToDoTask> {
ArrayList<ToDoTask> objects;
Context context;
int resource;
public ToDoAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<ToDoTask> objects) {
super(context, resource, objects);
this.objects = objects;
this.context = context;
this.resource = resource;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view = convertView;
ToDoHolder toDoHolder = null;
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row, parent, false);
toDoHolder = new ToDoHolder();
toDoHolder.rowTitle = (TextView) view.findViewById(R.id.rowTitle);
toDoHolder.rowDesc = (TextView) view.findViewById(R.id.rowDesc);
toDoHolder.rowDate = (TextView) view.findViewById(R.id.rowDate);
toDoHolder.rowIsDone = (CheckBox) view.findViewById(R.id.rowCheckBoxDone);
toDoHolder.rowIsDone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if(checked){
parent.getChildAt(position).setBackgroundColor(Color.parseColor("#8FE370"));
}
else
parent.getChildAt(position).setBackgroundColor(Color.WHITE);
}
});
view.setTag(toDoHolder);
} else {
toDoHolder = (ToDoHolder) view.getTag();
}
ToDoTask object = objects.get(position);
toDoHolder.rowTitle.setText(object.getTitle());
toDoHolder.rowDesc.setText(object.getDescription());
toDoHolder.rowDate.setText(object.getDate());
toDoHolder.rowIsDone.setChecked(object.getDone());
return view;
}
static class ToDoHolder {
TextView rowTitle;
TextView rowDesc;
TextView rowDate;
CheckBox rowIsDone;
}
}
Below is my MainActivity class which get details of single row element from "AddToDoTask" class.
public class MainActivity extends AppCompatActivity {
private final int requestCode = 1;
ArrayList<ToDoTask> lista = new ArrayList<>();
ToDoAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.buttonAdd);
ListView listView = (ListView) findViewById(R.id.listView);
adapter = new ToDoAdapter(this, R.layout.row, lista);
listView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), AddToDoTask.class);
startActivityForResult(intent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String title, description, date;
Boolean isDone;
if (requestCode == 1) {
if (null != data) {
title = data.getStringExtra("title");
description = data.getStringExtra("description");
date = data.getStringExtra("date");
isDone = data.getBooleanExtra("done", false);
lista.add(new ToDoTask(title, description, date, isDone));
adapter.notifyDataSetChanged();
}
}
}
}
public class ToDoAdapter extends ArrayAdapter<ToDoTask> {
private ArrayList<ToDoTask> objects;
private Context context;
private int resource;
private SparseBooleanArray checkedPositions = new SparseBooleanArray();
public ToDoAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<ToDoTask> objects) {
super(context, resource, objects);
this.objects = objects;
this.context = context;
this.resource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ToDoHolder toDoHolder;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.row, parent, false);
toDoHolder = new ToDoHolder();
toDoHolder.rowTitle = (TextView) convertView.findViewById(R.id.rowTitle);
toDoHolder.rowDesc = (TextView) convertView.findViewById(R.id.rowDesc);
toDoHolder.rowDate = (TextView) convertView.findViewById(R.id.rowDate);
toDoHolder.rowIsDone = (CheckBox) convertView.findViewById(R.id.rowCheckBoxDone);
convertView.setTag(toDoHolder);
} else {
toDoHolder = (ToDoHolder) convertView.getTag();
}
toDoHolder.rowTitle.setTag(position);
toDoHolder.rowIsDone.setTag(convertView);
toDoHolder.rowIsDone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
View view = (View) compoundButton.getTag();
TextView title = (TextView) view.findViewById(R.id.rowTitle);
int pos = (int) title.getTag();
if (checked) {
checkedPositions.put(pos, true);
view.setBackgroundColor(Color.parseColor("#8FE370"));
} else {
checkedPositions.put(pos, false);
view.setBackgroundColor(Color.WHITE);
}
}
});
ToDoTask object = objects.get(position);
toDoHolder.rowTitle.setText(object.getTitle());
toDoHolder.rowDesc.setText(object.getDescription());
toDoHolder.rowDate.setText(object.getDate());
toDoHolder.rowIsDone.setChecked(object.getDone() || checkedPositions.get(position));
return convertView;
}
private class ToDoHolder {
private TextView rowTitle;
private TextView rowDesc;
private TextView rowDate;
private CheckBox rowIsDone;
}
}
You must add a layout in your row xml file and put layout in toDoHolder and just change the layouts background color. You can access child views like
layout.findViewByID(int ID);

Information passing from one ListView item to another in my Adapter

I have a condition that checks if likeCount_int >= 4. If the condition is true, I unhide a TextView in the current item. Unfortunately, when I scroll fast, this TextView is unhidden on pretty much every other list item. How can I fix this is so there isn't data transfer between the list views?
public class MarketFeedAdapter extends ArrayAdapter<ParseObject> {
protected Context mContext;
protected List<ParseObject> mYeets;
private MarketFeedAdapter adapter;
ImageLoader profilePictureImageLoader;
public MarketFeedAdapter(Context context, List<ParseObject> yeets) {
super(context, R.layout.yeet_listview_item, yeets);
mContext = context;
mYeets = yeets;
this.adapter = this;
profilePictureImageLoader = new ImageLoader(new ProfilePictureFileCache(mContext));
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.yeet_listview_item, null);
holder = new ViewHolder();
holder.username = (TextView)convertView.findViewById(R.id.username);
holder.fullName = (TextView)convertView.findViewById(R.id.fullName);
holder.messageText = (TextView)convertView.findViewById(R.id.messageText);
holder.time = (TextView)convertView.findViewById(R.id.time);
holder.profilePicture = (ImageView) (convertView.findViewById(R.id.profilePicture));
holder.likeImage = (ImageView) convertView.findViewById(R.id.likeImage);
holder.likeCount = (TextView) convertView.findViewById(R.id.likeCount);
holder.premiumContent = (TextView) convertView.findViewById(R.id.premiumContent);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
final ParseObject yeets = mYeets.get(position);
Date createdAt = yeets.getCreatedAt();
long now = new Date().getTime();
String convertedDate = DateUtils.getRelativeTimeSpanString(createdAt.getTime(), now, DateUtils.SECOND_IN_MILLIS).toString();
holder.username.setText(yeets.getString(ParseConstants.KEY_SENDER_NAME));
if (!(yeets.getString(ParseConstants.KEY_SENDER_FULL_NAME).equals(""))) {
holder.fullName.setText(yeets.getString(ParseConstants.KEY_SENDER_FULL_NAME));
} else {
holder.fullName.setVisibility(View.GONE);
}
holder.messageText.setText(yeets.getString(ParseConstants.KEY_NOTIFICATION_TEXT));
holder.time.setText(convertedDate);
int likeCount_int = yeets.getInt(ParseConstants.KEY_LIKE_COUNT);
String likeCount_string = Integer.toString(likeCount_int);
holder.likeCount.setText(likeCount_string);
if (likeCount_int >= 4) {
holder.premiumContent.setVisibility(View.VISIBLE);
Typeface tf_bold = Typeface.createFromAsset(getContext().getAssets(), "fonts/Lato-Bold.ttf");
holder.premiumContent.setTypeface(tf_bold);
}
String profilePictureURL = yeets.getString(ParseConstants.KEY_SENDER_PROFILE_PICTURE);
// Asynchronously display the profile picture downloaded from Parse
if(profilePictureURL != null) {
profilePictureImageLoader.DisplayImage(profilePictureURL, holder.profilePicture, null);
} else {
holder.profilePicture.setImageResource(Integer.parseInt(String.valueOf(R.drawable.ic_profile_pic_add)));
}
holder.username.setOnClickListener(view -> {
view.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.image_click));
retrievePointerObjectId(yeets);
});
holder.fullName.setOnClickListener(view -> {
view.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.image_click));
retrievePointerObjectId(yeets);
});
holder.profilePicture.setOnClickListener(view -> {
view.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.image_click));
retrievePointerObjectId(yeets);
});
holder.likeImage.setOnClickListener(v -> {
v.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.image_click));
createLike(position);
});
convertView.setOnClickListener(v -> retrievePointerObjectIdForComment(yeets));
convertView.setOnLongClickListener(v -> {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
dialogBuilder.setTitle("Delete");
dialogBuilder.setMessage("Do you want to delete this Yeet?");
dialogBuilder.setPositiveButton("Yes", (dialog, which) -> {
deleteComment(position);
});
dialogBuilder.setNegativeButton("No", (dialog, which) -> {
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
return false;
});
return convertView;
}
// A view holder for all the iterative elements in our list, i.e. username, fullName, etc.
public static class ViewHolder {
TextView username;
TextView fullName;
TextView messageText;
TextView time;
ImageView profilePicture;
ImageView likeImage;
TextView likeCount;
TextView premiumContent;
}

List view is not displaying content

I have a simple task that is to take string input from Dialog then add it to listview with checkbox .
What happening is that , I entered test through dialog but it is not displaying after adding and also code doesn't have any error during runtime .
MainActivity.java
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
ListView list;
MyCustomAdapter dataAdapter ;
List<SubTasksModel> subTasksModelArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.heading);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
subTasksModelArrayList = new ArrayList<SubTasksModel>();
list = (ListView) findViewById(R.id.list);
dataAdapter = new MyCustomAdapter(this , R.layout.child_row_add_subtask , subTasksModelArrayList);
list.setAdapter(dataAdapter);
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.add_subtask_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.et_task);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Add Subtask", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
/*subTasksModelArrayList = new ArrayList<SubTasksModel>();*/
fillData(editText.getText().toString() , false);
Utility.setListViewHeightBasedOnChildren(list);
}
})
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void fillData(String s, boolean b) {
final SubTasksModel model = new SubTasksModel();
model.setTask(s);
model.setSelected(b);
subTasksModelArrayList.add(model);
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends BaseAdapter {
public List<SubTasksModel> subTasksModelList;
Context context;
private LayoutInflater mInflater;
public MyCustomAdapter(Context context, int resource, List<SubTasksModel> objects) {
this.context=context;
this.subTasksModelList=objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
LinearLayout linearLayout;
TextView task;
CheckBox cb;
}
#Override
public int getCount() {
return 0;
}
#Override
public SubTasksModel getItem(int position) {
return subTasksModelList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.child_row_add_subtask, null);
holder.task = (TextView) convertView.findViewById(R.id.tv_subtask);
holder.cb = (CheckBox) convertView.findViewById(R.id.cb_subtask);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayout01);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
final int pos = position;
holder.task.setText(subTasksModelList.get(position).getTask());
holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
subTasksModelList.get(pos).setSelected(isChecked);
}
});
/*Log.d("ArrayList"," : "+ subTasksModelList);
SubTasksModel subTasksModel = subTasksModelList.get(position);
holder.task.setText(subTasksModel.getTask());
holder.cb.setChecked(subTasksModel.isSelected());
holder.cb.setTag(subTasksModel);*/
return convertView;
}
}
SubTaskModel.java
public class SubTasksModel {
String task = "";
boolean selected = false;
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
// Utility class is just to set height of listview inside scrollview.
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
Log.d("Params are : " , " : "+ params);
listView.requestLayout();
}
}
#Override
public int getCount() {
return 0;
}
replace it with
#Override
public int getCount() {
return subTasksModelList.size();
}

Get parent layout from custom Adapter

Could anybody explain me, how to realize?
I have an activity with listview and footer with some elements(textview).
Listview built with custom adapter. Each listview item has few elements. And my question: how can i change textview in footer, from custom adapter, when i clicking on some listview's element?
Thx a lot!
/**** My adapter ****/
public class MyListAdapter extends ArrayAdapter<Product> implements UndoAdapter {
private final Context mContext;
private HashMap<Product, Integer> mIdMap = new HashMap<Product, Integer>();
ArrayList<Product> products = new ArrayList<Product>();
final int INVALID_ID = -1;
LayoutInflater lInflater;
String imagePath;
public MyListAdapter(Context context, int textViewResourceId, List<Product> prod) {
//super(context, textViewResourceId, prod);
super(prod);
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
for (int i = 0; i < prod.size(); i++) {
//add(prod.get(i));
mIdMap.put(prod.get(i),i);
}
}
#Override
public long getItemId(final int position) {
//return getItem(position).hashCode();
Product item = (Product) getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;;
Product p = getItem(position);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.item, null);
//convertView.setBackgroundResource(R.drawable.rounded_corners);
int currentTheme = Utils.getCurrentTheme(convertView.getContext());
switch (currentTheme) {
case 0:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
case 1:
convertView.setBackgroundResource(R.drawable.border);
break;
default:
convertView.setBackgroundResource(R.drawable.rounded_corners);
break;
}
holder = new ViewHolder();
holder.tvDescr = (TextView) convertView.findViewById(R.id.tvDescr);
holder.list_image = (ImageView) convertView.findViewById(R.id.list_image);
holder.products_amount = (TextView) convertView.findViewById(R.id.amountDigits);
holder.products_price = (TextView) convertView.findViewById(R.id.priceDigits);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
holder.unit = (TextView) convertView.findViewById(R.id.unit);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(p.getProductImageBitmap() != null && p.getProductImageBitmap() != "") {
Log.d("PATH -- ", p.getProductImageBitmap());
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
/*.showImageOnLoading(R.id.progress_circular)*/
.build();
imageLoader.displayImage(p.getProductImageBitmap(), holder.list_image, options);
} else {
holder.list_image.setImageResource(R.drawable.ic_launcher);
}
holder.tvDescr.setText(p.getProductName());
holder.ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String deletedItem = getItem(position).getProductName();
MyListAdapter.this.remove(getItem(position));
if (MyListAdapter.this.getCount() > 0) {
Toast.makeText(mContext, deletedItem + " " + mContext.getString(R.string.deleted_item), Toast.LENGTH_SHORT).show();
MyListAdapter.this.notifyDataSetChanged();
} else {
Toast.makeText(mContext,mContext.getString(R.string.sklerolist_empty), Toast.LENGTH_SHORT).show();
}
}
});
//Функционал для большой картинки продукта
//открывается новое активити с большой картинкой
holder.list_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imagePath = getItem(position).getProductImageBitmap();
if(imagePath != null && imagePath != "") {
Pattern normalPrice = Pattern.compile("^file");
Matcher m2 = normalPrice.matcher(imagePath);
if (m2.find()) {
Intent myIntent = new Intent(view.getContext(), ViewImage.class).putExtra("imagePath", imagePath);
view.getContext().startActivity(myIntent);
}
}
}
});
holder.products_price.setText(fmt(p.getProductPrice()));
holder.products_amount.setText(fmt(p.getProductAmount()));
holder.unit.setText(p.getProductUnit());
return convertView;
}
public static String fmt(double d){
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
static class ViewHolder {
ImageView list_image;
TextView tvDescr;
TextView products_amount;
TextView products_price;
TextView unit;
ImageView ivImage;
ProgressBar circleProgress;
}
#NonNull
#Override
public View getUndoView(final int position, final View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
if (view == null) {
//view = LayoutInflater.from(mContext).inflate(R.layout.undo_row, parent, false);
view = lInflater.inflate(R.layout.undo_row, parent, false);
}
return view;
}
#NonNull
#Override
public View getUndoClickView(#NonNull final View view) {
return view.findViewById(R.id.undo_row_undobutton);
}
public View getHeaderView(final int position, final View convertView, final ViewGroup parent) {
TextView view = (TextView) convertView;
//View view = convertView;
if (view == null) {
//view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.list_header, parent, false);
//view = lInflater.inflate(R.layout.list_header, parent, false);
}
//view.setText(mContext.getString(R.string.header, getHeaderId(position)));
return view;
}
public long getHeaderId(final int position) {
return position / 10;
}
}
Your ListView has a listener for the click events on list elements.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something when a list item is clicked
}
But if you want to pas something else back from the adapter to the Activity or the Fragment that contains that ListView and Adapter, you should create a simple interface and set it as listener to your adapter. After that, set click events on your rows from within the adapter, and notify the Activity or Fragment using your own interface.
For example you have the interface defined like this
public interface OnItemClickedCustomAdapter {
public void onClick(ItemPosition position);
}
and in your Adapter class you will have a private member
private OnItemClickedCustomAdapter mListener;
and a method used to set the listener
public void setOnItemClickedCustomAdapter(OnItemClickedCustomAdapter listener){
this.mListener = listener;
}
From your Activity or Fragment where your ListView is defined, and your adapter is set, you will be able to call setOnItemClickedCustomAdapter with this as parameter, and there you go. Your activity will now listen for your events. To trigger an event, just call mListener.onClick() from your custom adapter. You can pass back data you need back to the Activity or Fragment, and from there you have access to your Header or Footer directly, and you can change the text on them.

Wrong position in Custom Adapter

I have created a Custom Adapter to manage some Buttons inside each ListView item. If I scroll-down the list, and I click a button, the adapter take a wrong position.
LISTVIEW
item 1
item 2
item 3
item 4
item 5
item 6
item 7
POSITION AFTER CLICK
0
1
2
3
4
5
0
This is my adapter:
public DoubleListAdapter(Context context, ArrayList<DoubleListItems> items,
String Tag) {
super(context, 0, items);
this.Tag = Tag;
this.context = context;
this.items = items;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final int Position = position;
if (convertView == null) {
convertView = vi.inflate(R.layout.double_list_item, null);
holder = new ViewHolder();
final DoubleListItems i = (DoubleListItems) items.get(position);
holder.item = i;
holder.Icon = (ImageView) convertView
.findViewById(R.id.IconaDoubleList);
holder.Title = (TextView) convertView
.findViewById(R.id.TitoloDoubleList);
holder.SecondLineDesc = (TextView) convertView
.findViewById(R.id.SecondaLineaDesc);
holder.SecondLineValue = (TextView) convertView
.findViewById(R.id.SecondaLineaValue);
holder.ThirdLineDesc = (TextView) convertView
.findViewById(R.id.TerzaLineaDesc);
holder.ThirdLineValue = (TextView) convertView
.findViewById(R.id.TerzaLineaValue);
holder.Delete = (Button) convertView
.findViewById(R.id.ButtonDeleteItem);
holder.Set = (Button) convertView.findViewById(R.id.ButtonSetiItem);
holder.Delete.setTag(holder);
holder.Delete.setOnClickListener(new OnClickListener() {
holder.Set.setTag(holder);
holder.Set.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Log.e("DOUBLELIST ADAPTER ", "Position: " + Position);
String Code = i.getKey();
// String Code = holder.item.getKey();
Intent intent;
Costanti.curLocale = Costanti.LocaliLavorati.Item("L"
+ Code);
intent = new Intent(context, IncassiTab.class);
if (Costanti.curLocale != null) {
context.startActivity(intent);
} else {
Toast.makeText(context, "Locale nullo",
Toast.LENGTH_SHORT);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final DoubleListItems i = holder.item;
if (i != null) {
holder.Set.setVisibility(View.GONE);
holder.Delete.setVisibility(View.GONE);
holder.Icon.setImageResource(i.getIcon());
holder.Title.setText(i.getTitle());
holder.SecondLineDesc.setText(i.getSecondLineDesc());
if (i.getType().equals("N")) {
holder.SecondLineDesc.setTextColor(context.getResources()
.getColor(R.color.grigio));
}
if (!i.getSecondLineValue().equals("")) {
holder.SecondLineValue.setVisibility(View.VISIBLE);
holder.SecondLineDesc.setTextColor(context.getResources()
.getColor(R.color.orange));
holder.Icon.setImageResource(i.getIcon());
holder.Title.setText(i.getTitle());
holder.SecondLineDesc.setText(i.getSecondLineDesc());
holder.SecondLineValue.setText(i.getSecondLineValue());
if (!i.getThirdLineDesc().equals("")) {
holder.Set.setVisibility(View.VISIBLE);
holder.Delete.setVisibility(View.VISIBLE);
holder.ThirdLineDesc.setVisibility(View.VISIBLE);
holder.ThirdLineValue.setVisibility(View.VISIBLE);
holder.ThirdLineDesc.setText(i.getThirdLineDesc());
holder.ThirdLineValue.setText(i.getThirdLineValue());
holder.Delete.setVisibility(View.VISIBLE);
holder.Set.setVisibility(View.VISIBLE);
} else {
holder.ThirdLineDesc.setVisibility(View.GONE);
holder.ThirdLineDesc.setVisibility(View.GONE);
}
} else {
holder.SecondLineValue.setVisibility(View.GONE);
holder.ThirdLineDesc.setVisibility(View.GONE);
holder.ThirdLineValue.setVisibility(View.GONE);
holder.Set.setVisibility(View.GONE);
holder.Delete.setVisibility(View.GONE);
}
}
return convertView;
}
private class ViewHolder {
public ViewHolder() {
}
protected DoubleListItems item;
protected Button Delete;
protected Button Set;
protected ImageView Icon;
protected TextView Title;
protected TextView SecondLineDesc;
protected TextView SecondLineValue;
protected TextView ThirdLineDesc;
protected TextView ThirdLineValue;
}
This is the solution:
if (convertView == null) {
Your code
}else{
Your code
}
holder.Set.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Your code
}
}

Categories

Resources