Home » Android » android – How can a custom view get access to its activity?

android – How can a custom view get access to its activity?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a custom view and would like to access a String that is available in its activity. I’ve seen code that uses getContext() in the view class, but there is no method to access the String that has been made available to its activity via an intent. How to make a String in an activity available to its custom view?

How to&Answers:

The getContext() method in the View class returns the context that was passed on its constructor. Usually that’s the Activity you want (Activity extends Context).
So this probably works for you:

((Activity)getContext()).someMethod(...);

Answer:

I’m a noob to java and android still, so this may not work, but I’m just trying to help.

You should be able to pass in parameters to intents/activities using “putExtra” and “getExtra”, for example:

In your main activity:

 Intent EditDebtActivity = new Intent(getBaseContext(), EditDebt.class);
        EditDebtActivity.putExtra(DbAdapter.KEY_ROWID,dRowID);
        EditDebtActivity.putExtra(DbAdapter.KEY_DEBT, dName);
        EditDebtActivity.putExtra(DbAdapter.KEY_STARTINGAMOUNT, dStartAmount);
        EditDebtActivity.putExtra(DbAdapter.KEY_CURRENTAMOUNT, dCurrentAmount);
        EditDebtActivity.putExtra(DbAdapter.KEY_DUEDATE, dDueDate);
        EditDebtActivity.putExtra(DbAdapter.KEY_INTERESTRATE, dInterestRate);
        EditDebtActivity.putExtra(DbAdapter.KEY_MINPAYMENT, dMinPayment);
        startActivity(EditDebtActivity);

Then in the “onCreate” method in your new view, use the following:

 Bundle extras = getIntent().getExtras();
  dRowID = extras.getLong(DbAdapter.KEY_ROWID);
  String rowidname = extras.getString(DbAdapter.KEY_DEBT);
  currentamount = extras.getDouble(DbAdapter.KEY_CURRENTAMOUNT);
  startingamount = extras.getDouble(DbAdapter.KEY_STARTINGAMOUNT);
  duedate = extras.getInt(DbAdapter.KEY_DUEDATE);

obviously I’ve used my own code here, but I am passing row information into a new activity when a user clicks a button.

See this SO link for more info on using putextra and getextra: Sending arrays with Intent.putExtra

Hope this helps, it’s my first contribution back to the community 🙂