ListView setOnItemClicklistener NullPointerException - android

public class CustomAdapter extends ArrayAdapter<Plan> implements View.OnClickListener {
private ArrayList<Plan> planArrayList;
int position;
Context context;
private static class ViewHolder{
TextView workType;
TextView zone;
TextView division;
TextView station;
TextView Msg;
}
public CustomAdapter(ArrayList<Plan> plan,Context context){
super(context,R.layout.plan_list,plan);
this.planArrayList=plan;
this.context=context;
}
#Override
public void onClick(View v) {
}
private int lastPosition = -1;
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Plan plans = getItem(position);
ViewHolder viewHolder;
final View result;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null){
viewHolder = new ViewHolder();
//LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.plan_list,parent,false);
viewHolder.workType = (TextView) convertView.findViewById(R.id.plan_worktype);
viewHolder.zone = (TextView) convertView.findViewById(R.id.plan_zone);
viewHolder.division = (TextView) convertView.findViewById(R.id.plan_division);
viewHolder.station = (TextView) convertView.findViewById(R.id.plan_station);
viewHolder.Msg = (TextView) convertView.findViewById(R.id.)
result=convertView;
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
Animation animation = AnimationUtils.loadAnimation(context, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
Plan plan = planArrayList.get(position);
lastPosition = position;
viewHolder.workType.setText(plans.getWorkType());
viewHolder.zone.setText(plans.getZone());
viewHolder.division.setText(plans.getDiv());
viewHolder.station.setText(plans.getSTA());
viewHolder.workType.setText(plan.getWorkType());
viewHolder.zone.setText(plan.getZone());
viewHolder.division.setText(plan.getDiv());
viewHolder.station.setText(plan.getSTA());
if (this.position == position){
View view2 = inflater.inflate(R.layout.list_dialog,null);
TextView worktype= (TextView) view2.findViewById(R.id.dlg_worktype);
TextView zone = (TextView) view2.findViewById(R.id.dlg_zone);
TextView div = (TextView) view2.findViewById(R.id.dlg_division);
TextView sta = (TextView) view2.findViewById(R.id.dlg_station);
TextView msg = (TextView) view2.findViewById(R.id.dlg_msg);
worktype.setText(plan.getWorkType());
zone.setText(plan.getZone());
div.setText(plan.getDiv());
sta.setText(plan.getSTA());
msg.setText(plan.getMsg());
return view2;
}
return convertView;
}
public void selectedItem(int position){
this.position=position;
}
}
When I called setOnItemClickListener on listView item those item values need to display in dialog box.
By the above code I'm getting java.lang.NullPointerException: Attempt to read from field 'android.widget.TextView com.example.nsurekha.entry_ex.CustomAdapter$ViewHolder.workType' on a null object reference

If you want to use onClick on listView
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
String title=adapter.getItem(arg2).getTitle();
String description=adapter.getItem(arg2).getDescription();
String addedby=adapter.getItem(arg2).getAddedby();
}
});
Now you can easily show dialogbox with the desired data. Hope it works for you.

Related

How to change my TextView value by clicking ImageButton in ListView

This is my listview, my problem is why I'm trying to click on my ImageButton(in listview) but the textview(in listview) never change the value that what I want. It's take my whole morning, can someone please help me, Thanks.
public class ViewAdapter extends BaseAdapter implements Filterable {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return pl.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listproduct, null);
}
final TextView ProductCode = (TextView) convertView.findViewById(R.id.productcode);
ProductCode.setText("" + pl.get(position).getProductCode());
final TextView Qty = (TextView) convertView.findViewById(R.id.qty);
Qty.setText("" + pl.get(position).getQty());
final TextView Description = (TextView) convertView.findViewById(R.id.description);
Description.setText("" + pl.get(position).getProductName());
final String p = Description.getText().toString();
final TextView Price = (TextView) convertView.findViewById(R.id.price);
Price.setText("" + pl.get(position).getProductPrice());
final ImageButton minus = (ImageButton) convertView.findViewById(R.id.minus);
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Qty.setText("testing")// textview never change to "testing"
}
});
notifyDataSetChanged();
return convertView;
}
Please try your code with holder just like follows
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_entry, null);
holder = new ViewHolder();
holder.nameTextView = (TextView) convertView.findViewById(R.id.person_name);
holder.surnameTextView = (TextView) convertView.findViewById(R.id.person_surname);
holder.personImageView = (ImageView) convertView.findViewById(R.id.person_image);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Person person = getItem(position);
holder.nameTextView.setText(person.getName());
holder.surnameTextView.setText(person.getSurname());
//holder.personImageView.setImageBitmap(person.getImage());
return convertView;
}
Then click as follows
holder.personImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.nameTextView.setText("testing")// textview never change to "testing"
}
});
Use this code :
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listproduct, null);
}
final TextView ProductCode = (TextView) convertView.findViewById(R.id.productcode);
ProductCode.setText("" + pl.get(position).getProductCode());
final TextView Qty = (TextView) convertView.findViewById(R.id.qty);
final TextView Description = (TextView) convertView.findViewById(R.id.description);
Description.setText("" + pl.get(position).getProductName());
final String p = Description.getText().toString();
final TextView Price = (TextView) convertView.findViewById(R.id.price);
Price.setText("" + pl.get(position).getProductPrice());
ImageButton minus = (ImageButton) convertView.findViewById(R.id.minus);
minus.setTag(position);
minus.setOnClickListener(clickButton);
return convertView;
}
private View.OnClickListener clickButton = new View.OnClickListener() {
#Override
public void onClick(View v) {
Object tag =v.getTag();
if(tag!=null)
{
int pos = (Integer)tag;
Qty.setText(pl.get(position).getQty());
notifyDataSetChanged();
}
}
} ;
As far as i understand from your question this cannot be done because once you populate the data in custom listView you have recreate it or call the custom listView again with text display you want to change!
Basically you should use RecyclerView,but if you still want to use the listView, use the view-holder approach as in this link below:
Optimize list view
And you should never ever call notifyDataSetChanged() in getView method as its called multiple time as your listview scrolls

Dynamically change custom list item background

I am creating a custom list view with favorite functionality, but I don't know how to change favorite image background on click. When I simply change the background of favorite icon than it automatically change background of another favorite image background at the time of scrolling. Please check below code :
public class CustomArrayAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater = null;
ArrayList<Customlist> list;
DecimalFormat formatter = new DecimalFormat("#,##,###");
public CustomArrayAdapter(Activity a, ArrayList<Customlist> list) {
activity = a;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.list = list;
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
TextView txt_unit, txt_state, txt_price, term_left, customr;
TextView install_date;
final ImageView fav;
View view = convertView;
if (convertView == null)
view = inflater.inflate(R.layout.list_item, null);
customr = (TextView) view.findViewById(R.id.customr);
txt_state = (TextView) view.findViewById(R.id.txt_state);
install_date = (TextView) view.findViewById(R.id.install_date);
term_left = (TextView) view.findViewById(R.id.term_left);
txt_price = (TextView) view.findViewById(R.id.txt_price);
fav = (ImageView) view.findViewById(R.id.fav);
txt_unit = (TextView) view.findViewById(R.id.txt_unit);
fav.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// fav = (ImageView)v.findViewById(R)
fav.setBackgroundResource(R.drawable.favourite_select);
Toast.makeText(activity, "click", 1).show();
}
});
// set values
customr.setText(list.get(position).getCUSTOMER());
txt_state.setText(list.get(position).getSTATE_NAME());
install_date.setText(list.get(position).getINSTALL_DATE());
term_left.setText(list.get(position).getTREM_LEFT());
String price = formatter.format(Integer.parseInt(list.get(position)
.getRUPEES()));
return view;
}
}
First, you need to implement the adapter on ViewHolder pattern:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHoldler holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(ctx).inflate(
R.layout.frag_home_gridview_item, null, false);
holder = new ViewHoldler();
holder.iv = (ImageView) convertView
.findViewById(R.id.gridview_item_label);
holder.tv = (TextView) convertView
.findViewById(R.id.gridview_item_name);
convertView.setTag(holder);
} else {
holder = (ViewHoldler) convertView.getTag();
}
holder.tv.setText(getItem(position));
holder.iv.setImageResource(this.ids[position]);
return convertView;
}
private class ViewHoldler {
ImageView iv;
TextView tv;
}
Second, use partial refreshment mechanism to change the target View's background:
private void refreshPartially(int position){
int firstVisiblePosition = listview.getFirstVisiblePosition();
int lastVisiblePosition = listview.getLastVisiblePosition();
if(position>=firstVisiblePosition && position<=lastVisiblePosition){
View view = listview.getChildAt(position - firstVisiblePosition);
if(view.getTag() instanceof ViewHolder){
ViewHolder vh = (ViewHolder)view.getTag();
//holder.play.setBackgroundResource(resId);//Do something here.
...
}
}
}
Third, add AdapterView.OnItemClickListener to your ListView:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
refreshPartially(position);
}
});
You need to implement the adapter on ViewHolder pattern:
http://www.vogella.com/tutorials/AndroidListView/article.html

Modify a textview value in a custom listview after clicking

This listview has an adapter that is linked to a layout for each row (itemrow.xml)
The price value (500-250 300) is a textview
How can we access to it, to modify it, once clicked on a button ?
lllllllllllllllllllllllllllllllll
Android
Price: 500
lllllllllllllllllllllllllllllllll
Php
Price: 250
lllllllllllllllllllllllllllllllll
C++
Price: 300
lllllllllllllllllllllllllllllllll
public class CommandeAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<Commande> listCommande;
public CommandeAdapter(Context context, List<Commande> listCommande) {
this.context = context;
this.listCommande = listCommande;
}
public int getCount() {
return listCommande.size();
}
public Object getItem(int position) {
return listCommande.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Commande entry = listCommande.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listitem_row, null);
}
TextView tvNom = (TextView) convertView.findViewById(R.id.textView1);
tvNom.setText(entry.getNom());
TextView tvPrixU = (TextView) convertView.findViewById(R.id.textView2);
tvPrixU.setText(entry.getPrixU());
TextView tvqte = (TextView) convertView.findViewById(R.id.textView4);
tvqte.setText(entry.getQte());
TextView tvSomme = (TextView) convertView.findViewById(R.id.textView5);
tvSomme.setText(String.format("%.03f", entry.getSomme()));
return convertView;
}
#Override
public void onClick(View view) {
Commande entry = (Commande) view.getTag();
listCommande.remove(entry);
// listCommande.remove(view.getId());
notifyDataSetChanged();
}
private void showDialog(Commande entry) {
// Create and show your dialog
// Depending on the Dialogs button clicks delete it or do nothing
}
}

Android ListView with Custom Array adaptor image reoccuring

i am trying to setVisible a play icon on click of listview item just like in music player.
I am using a custom array adapter, all is working good but when i scroll up/down and select any item on the list the previous play icon dosent go away.
But if i dont scroll and just click on the item it works perfectly fine.
OnclickListener :
listChannels.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if (oldView != null) {
oldView.setDrawingCacheEnabled(true);
ImageView icon = (ImageView) oldView
.findViewById(R.id.icon);
icon.setImageBitmap(null);
icon.setVisibility(ImageView.GONE);
icon.invalidate();
}
oldView = arg1;
selectedItem = arg2;
ImageView icon = (ImageView) arg1.findViewById(R.id.icon);
icon.setImageResource(R.drawable.play);
icon.setVisibility(ImageView.VISIBLE);
}
});
Array Adapter :
private class ListArrayAdapter extends ArrayAdapter<String> {
public ListArrayAdapter(Context context, int textViewResourceId,
String[] arrTitle) {
super(context, textViewResourceId, arrTitle);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.listitem_row, parent, false);
TextView label = (TextView) row.findViewById(R.id.station);
ImageView imageView = (ImageView) row
.findViewById(R.id.imageViewDisplay);
String areaStr = feeds.get(position).getStrLocation();
imageLoader.DisplayImage(feeds.get(position).getStrImage()
.toString(), activity, imageView);
if (!areaStr.equals("")) {
TextView area = (TextView) row.findViewById(R.id.area);
area.setText(areaStr);
area.setVisibility(TextView.VISIBLE);
}
if (selectedItem == position) {
ImageView icon = (ImageView) row.findViewById(R.id.icon);
icon.setImageResource(R.drawable.play);
icon.setVisibility(ImageView.VISIBLE);
}
return row;
}
}
You shoud have your custom adapter class like this:
public class ListArrayAdapter extends ArrayAdapter<String>{
Context context;
ArrayList<String> array=new ArrayList<String>();
LayoutInflater mInflater;
int selected;
public ListArrayAdapter(Context context,int textViewResourceId,ArrayList<String> list)
{
super(context, textViewResourceId, list);
this.context=context;
array=list;
mInflater = LayoutInflater.from(context);
selected=list.size()+1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.label = (TextView) convertView.findViewById(R.id.station);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageViewDisplay);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.area = (TextView) row.findViewById(R.id.area);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
// your code goes here
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
selected=position;
holder.icon.setImageResource(R.drawable.play);
holder.icon.setVisibility(View.VISIBLE);
}
});
if(selected==position)
{
holder.icon.setImageResource(R.drawable.play);
holder.icon.setVisibility(View.VISIBLE);
}
else
holder.icon.setVisibility(View.GONE);
return convertView;
}
static class ViewHolder
{
TextView label;
ImageView imageView;
ImageView icon;
TextView area;
}
}
and you don't need to worry for your this proble in your listview.onItemClick().

Problem with ListView. When i changue the color of an item (pressing on it) and i scrolldown, another item appears with color changed

I'm having a very strange problem with my custom listview.
This Listview shows a lot of names and some more data, and each item haves an onClick listener, and when i press in one item, that item get's the background color changued to RED. ( arg1.setBackgroundColor(Color.RED); )
But something isn't working properly, because if i scrolldown the listview, another item appears colored on near of the bottom part of the list.
this is my code:
public class StartingSquad extends Activity {
public static List<Player> Players = new ArrayList<Player>();
public int selectedPosition=-1;
ListView l1;
private TextView TeamPowerValue=null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication.updateStartingSquadOnPlayers(MyApplication.getPlayerTeam(),this);//actualizo los titulares
Players=MyApplication.getPlayerTeam().getPlayers();
setContentView(R.layout.startingsquad);
TeamPowerValue = (TextView) findViewById(R.id.TeamPowerValue);
l1 = (ListView) findViewById(R.id.ListView01);
l1.setAdapter(new EfficientAdapter(this));
TeamPowerValue.setText(""+MyApplication.getPlayerTeam().getPower());
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//Toast.makeText(getBaseContext(), "You clciked "+Players.get(arg2).getName(), Toast.LENGTH_SHORT).show();
if (selectedPosition==-1) //si no hay ningun item seleccionado ya
{
arg1.setSelected(true);
//arg1.setBackgroundResource(R.drawable.bg3);
arg1.setBackgroundColor(Color.RED);
selectedPosition=arg2;
}
else //si ya habiamos seleccionado un jugador
{
MyApplication.getPlayerTeam().changePlayerPositions(selectedPosition, arg2);
selectedPosition=-1;
MyApplication.updateStartingSquadOnPlayers(MyApplication.getPlayerTeam(),StartingSquad.this);//actualizo los titulares
MyApplication.getPlayerTeam().calculatePower();
TeamPowerValue.setText(""+MyApplication.getPlayerTeam().getPower());
l1.setAdapter(new EfficientAdapter(StartingSquad.this));
}
}
});
}
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return Players.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.startingsquadlistview, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.PlayerPosition);
holder.text2 = (TextView) convertView.findViewById(R.id.PlayerName);
holder.text3 = (TextView) convertView.findViewById(R.id.PlayerPower);
holder.text4 = (TextView) convertView.findViewById(R.id.PlayerStartingSquad);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(Players.get(position).getPosition());
holder.text2.setText(Players.get(position).getName());
holder.text2.setTextColor(Players.get(position).NameColor);
holder.text3.setText(""+Players.get(position).getPower());
holder.text4.setText("XX");
return convertView;
}
static class ViewHolder {
TextView text;
TextView text2;
TextView text3;
TextView text4;
}
}
}
Do background change not in onItemSelected but in adater getView().
if(position == selectedPosition) {
convertView.setBackgroundColor(context.getResources().getColor(R.color.red));
} else {
convertView.setBackgroundColor(context.getResources().getColor(R.color.default));
}
Try to remove this line:
l1.setAdapter(new EfficientAdapter(StartingSquad.this));
If you can't, tell me why?
One more thing: Edit this function:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View convertViews;
if (convertView == null) {
convertViews = mInflater.inflate(R.layout.startingsquadlistview, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.PlayerPosition);
holder.text2 = (TextView) convertView.findViewById(R.id.PlayerName);
holder.text3 = (TextView) convertView.findViewById(R.id.PlayerPower);
holder.text4 = (TextView) convertView.findViewById(R.id.PlayerStartingSquad);
convertViews.setTag(holder);
} else {
convertViews = convertView;
holder = (ViewHolder) convertViews.getTag();
}
holder.text.setText(Players.get(position).getPosition());
holder.text2.setText(Players.get(position).getName());
holder.text2.setTextColor(Players.get(position).NameColor);
holder.text3.setText(""+Players.get(position).getPower());
holder.text4.setText("XX");
return convertViews;
}

Categories

Resources