Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get variable on activity from BaseAdapter Android

Im having a variable, bill_id on MainActivity. Then on MainActivity, I also has list view category, i put onItemClick on CategoryListAdapter. Here, when i click the category i want to reload the activity, which is new intent, and also pass variables, i want to pass category_id and bill_id(which is from MainActivity)

how can i get bill_id value from BaseAdapter?

here my snippet:

final int category_id = listData.get(position).getID();
        final String category_name = listData.get(position).get_name();

        holder.btnCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                Log.d(TAG, "click category:"+category_id);
                Log.d(TAG, "category selected:"+category_name);

                // get cat id, reload with its id
                db = new DatabaseHelper(aContext);

                // bring variable id, to POS interface
                Intent intent = new Intent(aContext, MainActivity.class);
                intent.putExtra("category_id", category_id);
                v.getContext().startActivity(intent);
            }
        });
like image 297
Gabriel Avatar asked Mar 22 '26 12:03

Gabriel


1 Answers

It is simple. Pass the values from your Activity to the Adapter using the adapter's constructor. This is what the constructors are for.

Like in your activity,

MyAdapter myAdapter = new MyAdapter(variable1, variable2);

Now in your adapter,

private int variable1, variable2;

// Constructor
public MyAdapter(int var1, int var2){
    this.variable1 = var1;
    this.variable2 = var2;
}

You can now easily use these variables in your click listener and pass them to the new intent.

You can also use setters for these variables in the adapter like,

public void setVariable1(int value){
    this.variable1 = value;
}

public void setVariable2(int value){
    this.variable2 = value;
}

And from your activity, do something like this whenever needed,

myAdapter.setVariable1(10);

So, these are the ways for you to access your variables from your activity inside your adapter.

like image 180
Aritra Roy Avatar answered Mar 24 '26 05:03

Aritra Roy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!