Search code examples
androidcheckboxbaseadapter

How to call functions from a custom base adapter


I have this code in my custom base adapter. I have a check boxes on each row in a list view, which are working fine and i have them linking with my database. However, when the check box is ticked i want to update the contents of a textview which is in the main activity this custom base adapter was started from.

 public View getView(final int position, View convertView, ViewGroup parent) {
  ViewHolder holder;

  if (convertView == null) {
   convertView = mInflater.inflate(R.layout.custom_row_view, null);
   holder = new ViewHolder();

   holder.bought = (CheckBox) convertView.findViewById(R.id.checkbox_bought);

   convertView.setTag(holder);
  } else {
   holder = (ViewHolder) convertView.getTag();
  }


  holder.bought.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
          // TODO Auto-generated method stub
          if(((CheckBox)v).isChecked()){
             //update textview in activity
          }else{

          }
      }
  });

Here is the function i would like to call when the check box is ticked, which is also where you see the custom base adapter beginning shown above.

  private void fillData() {
      db.updateTag(tag);

      totalCostView.setText(String.valueOf(tag.cost));
        listOfTodos = db.getAllToDosByTag(nameOfList);

        final ListView lv1 = (ListView) findViewById(R.id.listItems);
        lv1.setAdapter(new MyCustomBaseAdapter(this, list, tag));

    }

Solution

  • You can create getInstance method in your activity then call the method through it as following:

    class MainActivity extends Activity{
       private static MainActivity sMainActivity;
    
       @override
       private void onCreate(Bundle bundle){
           sMainActivity = this;
    

    And create the get method

    public static MainActivity getInstance() {
            return sMainActivity;
    }
    

    Then in your adapter call the following line:

    MainActivity.getInstance().fillData();
    

    Note: Make sure that the activity is currently opened to avoid any NullPointerExceptions