On Button Click how to increment counter and show

2020-04-16 03:46发布

问题:

I am working on a shopping cart assignment for that I have created a custom ListView that contains the Picture, Price and Add to Cart button in each row. I also have a textview at the top which increments everytime the user presses the Add to cart. The Button in every row is perfectly working fine but I don't know how to increment the counter and set it to the textview as whenever I do this under onClick event I get runtime error. I am sharing with you the code.

package uet.cs08.bll;

import java.util.ArrayList;

import uet.cs08.android.R;
import uet.cs08.android.mainActivity2;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class itemBaseAdapter extends BaseAdapter  {

 public int count = 5;
 private ArrayList<ItemInfo> itemList;
 private LayoutInflater mInflater;

 public itemBaseAdapter(Context context, ArrayList<ItemInfo> itemList){
     this.itemList=itemList;
     mInflater= LayoutInflater.from(context);

 }
@Override
public int getCount() {
    return itemList.size();

}

@Override
public Object getItem(int idx) {
     return itemList.get(idx);
}

@Override
public long getItemId(int idx) {
    // TODO Auto-generated method stub
    return idx;
}

@Override
public View getView(int idx,  View convertView, ViewGroup parent) {
    final ViewHolder holder;
    if(convertView==null){

        convertView=mInflater.inflate(R.layout.item_list_row, null);
        holder = new ViewHolder();
        holder.txtItemName=(TextView)  convertView.findViewById(R.id.itemName);
        holder.txtPic=(ImageView) convertView.findViewById(R.id.pic);
        holder.txtPrice=(TextView) convertView.findViewById(R.id.price);
        holder.counter = (TextView) convertView.findViewById(R.id.tvCount);
        Button btn = (Button) convertView.findViewById(R.id.Cart);
        final TextView tv = (TextView)convertView.findViewById(R.id.tvCount);


        btn.setOnClickListener(new View.OnClickListener() {
        @Override
            public void onClick(View v) {

                 count = Integer.parseInt((String)tv.getText());
                 count++;
                 tv.setText("" + count);


        }
        });
            //tv.setText(""+count);         
            convertView.setTag(holder);
    }else
    {
           holder = (ViewHolder) convertView.getTag();
    }

    holder.txtItemName.setText(itemList.get(idx).itemName);
    holder.txtPic.setImageResource(itemList.get(idx).pic);
    holder.txtPrice.setText(""+itemList.get(idx).price);
    holder.counter.setText(itemList.get(idx).count);

    return convertView;
}


class ViewHolder {
      TextView txtItemName;
      ImageView txtPic;
      TextView txtPrice;
      TextView counter;
     }

} ` Here is the logCat.

03-20 16:16:38.853: D/AndroidRuntime(2759): Shutting down VM
03-20 16:16:38.853: W/dalvikvm(2759): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-20 16:16:38.883: E/AndroidRuntime(2759): FATAL EXCEPTION: main
03-20 16:16:38.883: E/AndroidRuntime(2759): java.lang.NullPointerException
03-20 16:16:38.883: E/AndroidRuntime(2759):     at uet.cs08.bll.itemBaseAdapter$1.onClick(itemBaseAdapter.java:61)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at android.view.View.performClick(View.java:2485)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at android.view.View$PerformClick.run(View.java:9080)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at android.os.Handler.handleCallback(Handler.java:587)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at android.os.Looper.loop(Looper.java:123)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at java.lang.reflect.Method.invokeNative(Native Method)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at java.lang.reflect.Method.invoke(Method.java:507)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-20 16:16:38.883: E/AndroidRuntime(2759):     at dalvik.system.NativeStart.main(Native Method)

回答1:

Make sure you have reference to your TextView in xml.

Connect it (using findViewById()) inside onCreate() of Activity only, and you may pass it to your Adapter (i.e making a class field and setter getter method), if Adapter is a separate class.

and dont do this inside getView() of Adapter, remove this line.

final TextView tv  = (TextView)convertView.findViewById(R.id.tvCount);

you will pass your TextView from Activity to Adapter using constructor or setter getter method, will keep a reference using class Adapter's class level variable and the what you will do inside onClick() of Button is:

btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
          count++;
         yourClassLevelTextView.setText(String.valueOf(count));
     }});

EDIT:

how you will pass TextView to Adapter

public class YourAdapter extends BlahBlahBlah
{
     private TextView yourClassLevelTextView;
     public void setTextView(TextView textViewFromActivity)
     {
         this.yourClassLevelTextView = textViewFromActivity;
     }
}

and in Activity do something like this:

YourAdapter adapter = new YourAdapter(blah, blah, blah);
adapter.setTextView(yourTextViewInActivity);
listView.setAdapter(adapter);


回答2:

Your tv TextView isn't in the list row layout(where you search for it right now). You'll have to look for it in the activity layout if you declared it there(or in the layout where you declared it):

final TextView tv  = (TextView)findViewById(R.id.tvCount);


回答3:

Hi I guess count textview in your code not belongs to holder that count text view also should display through holder



回答4:

we have to set value runOnUiThread of that Controls. like this.. May this help you.

btn.setOnClickListener(new View.OnClickListener() 
{

            @Override
            public void onClick(View v) {
                    count++;
                   setTimertext(count);

        }
        });

public void setTimertext(String strValue) {         
        runOnUiThread(new Runnable() {
            public void run() {

                txt.setText(String.valueOf(strValue));    
            }
        });
    }