I am integrating Telr payment gateway in my app. I have used code from there dummy project which is working fine, I used their code in my fragment but it is throwing null context error. I have tried everything like "getContext" , "getApplicationContext" etc. but showing me error that context is null
Code :
public void sendMessage() {
Intent intent = new Intent(getActivity(), WebviewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.putExtra(WebviewActivity.EXTRA_MESSAGE, getMobileRequest());
intent.putExtra(WebviewActivity.SUCCESS_ACTIVTY_CLASS_NAME, "com.marketplace.activity.SuccessTransationActivity");
intent.putExtra(WebviewActivity.FAILED_ACTIVTY_CLASS_NAME, "com.marketplace.activity.FailedTransationActivity");
intent.putExtra(WebviewActivity.IS_SECURITY_ENABLED, isSecurityEnabled);
startActivity(intent);
}
There is a variable 'a' that exists in TelrApplication class.
extend your application with TelrApplication. This will resolve your problem.
public class TelrApplication extends Application {
private static Context a;
public TelrApplication() {
}
public void onCreate() {
super.onCreate();
Log.d("Hany", "Context Started....");
a = this.getApplicationContext();
}
public static Context a() {
return a;
}
}
I have created a simple custom dialog class. In further code I want to run new Intent:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345"));
startActivity(intent);
But the problem is whenever I call to change into that Intent I always get null in getOwnerActivity() - how to properly call that method?
public class AddToQueueDialog extends Dialog implements View.OnClickListener {
Activity mActivity;
private final String android_id = Settings.Secure.getString(getContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
public Activity getmActivity() {
return mActivity;
}
public void setmActivity(Activity mActivity) {
this.mActivity = mActivity;
}
public AddToQueueDialog(Context context, WashLocation washLocation) {
super(context);
setWashLocation(washLocation);
setmActivity(getOwnerActivity());
}
If you will check the source code and the activity it returns is set only in setOwnerActivity(Activity activity) which is not called anywhere. So if you want getOwnerActivity() to return value different than null, you have to change your constructor like following
public AddToQueueDialog(Context context, WashLocation washLocation) {
super(context);
if (context instanceof Activity) {
setOwnerActivity((Activity) context);
}
setWashLocation(washLocation);
setmActivity(getOwnerActivity());
}
You cant call the getOwnerActivity() in Oncreate
If you try to get owner from the constructor, Android hasn't hooked it yet, so you have no owner yet.
try this instead
public void onAttachedToWindow() {
super.onAttachedToWindow();
// getOwnerActivity() should be defined here if called via showDialog(), so do the related init here
Activity owner = getOwnerActivity();
if (owner != null) {
// owner activity defined here
}
}
context is the owning Activity. Your constructor is called with context. This is the owning Activity.
First, I am an android rookie, so my solution ways can be found awkward, and i am open to suggestions.
I am trying to create a game manager object that handles all transitions between activities. And my purpose is that while in an activity, menuOut method will call the changeActivity method of GameManager object with nextActivity argument and changeActivity will start that Activity. I am getting errors consistently, and did not find a solution.
Here is my source codes:
GameManager:
public class GameManager{
public SplashScreen splash = new SplashScreen();
public MainScreen main = new MainScreen();
public LoadingScreen load = new LoadingScreen();
Context tempContext;
public GameManager(Context base) {
super();
tempContext = base;
}
public void start(){
createScreens();
Intent intent = new Intent(tempContext, splash.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
tempContext.startActivity(intent);
}
public void createScreens() {
//here is the method that i am trying to find a solution
((SplashScreen)splash.getContext()).setGameClass(this);
((MainScreen)main.getContext()).setGameClass(this);
((LoadingScreen)load.getContext()).setGameClass(this);
}
public void changeMenu(MenuType nextMenu, MenuType previousMenu){
Intent intent2;
switch(nextMenu){
case MAIN_SC:
tempContext = main.getContext();
intent2.setClass(tempContext, main.getClass());
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
tempContext.startActivity(intent2);
case GAME_LOADING_SC:
tempContext = load.getContext();
intent2.setClass(tempContext, load.getClass());
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
tempContext.startActivity(intent2);
default:
break;
}
}
}
And here is SplashScreen activity:
public class SplashScreen extends Activity {
public Context context = this;
public GameManager gameman;
private static final int SPLASH_DURATION = 4000;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
splash();
menuOut();
}
public Context getContext() {
return this;
}
public void splash() {
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setBackgroundResource(R.drawable.game_loop_splash);
setContentView(ll);
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, SPLASH_DURATION);
}
public void setGameClass(GameManager game){
gameman = game;
}
private void menuOut(){
gameman.changeMenu(MenuType.GAME_LOADING_SC, MenuType.GAME_SPLASH_SC);
this.onDestroy();
}
}
I can not return to the GameManager and call the changeMenu method.
I am very exhausted to get null pointer exceptions.
Any idea?
From what I read, you are trying to implement a singleton pattern. There are two ways I'd recommend to do that on android:
Extend the Application class, register your class in the manifest and use getApplication() in your activities to get access to it:
// In MyApplicationSubclass.java:
public final class MyApplicationSubclass extends Application {
/* ... */
public void myMethod() {
// insert some code here
}
/* ... */
}
// From your Activity:
((MyApplicationSubclass) this.getApplication()).myMethod();
Use a "normal" java singleton pattern, e.g. use a private constructor and keep one static instance within your GameManager class (this is the way the Android docs recommend, but I personally prefer the first way when having something that is logically bound to the Application).
Also, if you're only using your central class to do static stuff, you can just mark all its method as static and access them directly. Transfer Context objects as parameters to these methods, and you should be able to start activities without any static variables (which are sometimes hard to implement properly in Android, as your VM might get restarted from time to time).
This one has me stumped.
I need to call an activity method from within a custom layout class. The problem with this is that I don't know how to access the activity from within the layout.
ProfileView
public class ProfileView extends LinearLayout
{
TextView profileTitleTextView;
ImageView profileScreenImageButton;
boolean isEmpty;
ProfileData data;
String name;
public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
{
super(context, attrs);
......
......
}
//Heres where things get complicated
public void onClick(View v)
{
//Need to get the parent activity and call its method.
ProfileActivity x = (ProfileActivity) context;
x.activityMethod();
}
}
ProfileActivity
public class ProfileActivityActivity extends Activity
{
//In here I am creating multiple ProfileViews and adding them to the activity dynamically.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_activity_main);
}
public void addProfilesToThisView()
{
ProfileData tempPd = new tempPd(.....)
Context actvitiyContext = this.getApplicationContext();
//Profile view needs context, null, name and a profileData
ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
profileLayout.addView(pv);
}
}
As you can see above, I am instantiating the profileView programatically and passing in the activityContext with it. 2 questions:
Am i passing the correct context into the Profileview?
How do I get the containing activity from the context?
From your Activity, just pass in this as the Context for your layout:
ProfileView pv = new ProfileView(this, null, temp, tempPd);
Afterwards you will have a Context in the layout, but you will know it is actually your Activity and you can cast it so that you have what you need:
Activity activity = (Activity) context;
This is something that I have used successfully to convert Context to Activity when operating within the UI in fragments or custom views. It will unpack ContextWrapper recursively or return null if it fails.
public Activity getActivity(Context context)
{
if (context == null)
{
return null;
}
else if (context instanceof ContextWrapper)
{
if (context instanceof Activity)
{
return (Activity) context;
}
else
{
return getActivity(((ContextWrapper) context).getBaseContext());
}
}
return null;
}
No
You can't
There are two different contexts in Android. One for your application (Let's call it the BIG one) and one for each view (let's call it the activity context).
A linearLayout is a view, so you have to call the activity context. To call it from an activity, simply call "this". So easy isn't it?
When you use
this.getApplicationContext();
You call the BIG context, the one that describes your application and cannot manage your view.
A big problem with Android is that a context cannot call your activity. That's a big deal to avoid this when someone begins with the Android development. You have to find a better way to code your class (or replace "Context context" by "Activity activity" and cast it to "Context" when needed).
Regards.
Just to update my answer. The easiest way to get your Activity context is to define a static instance in your Activity. For example
public class DummyActivity extends Activity
{
public static DummyActivity instance = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Do some operations here
}
#Override
public void onResume()
{
super.onResume();
instance = this;
}
#Override
public void onPause()
{
super.onPause();
instance = null;
}
}
And then, in your Task, Dialog, View, you could use that kind of code to get your Activity context:
if (DummyActivity.instance != null)
{
// Do your operations with DummyActivity.instance
}
And in Kotlin:
tailrec fun Context.activity(): Activity? = when {
this is Activity -> this
else -> (this as? ContextWrapper)?.baseContext?.activity()
}
If you like to call an activity method from within a custom layout class(non-Activity Class).You should create a delegate using interface.
It is untested and i coded it right . but i am conveying a way to achieve what you want.
First of all create and Interface
interface TaskCompleteListener<T> {
public void onProfileClicked(T result);
}
public class ProfileView extends LinearLayout
{
private TaskCompleteListener<String> callback;
TextView profileTitleTextView;
ImageView profileScreenImageButton;
boolean isEmpty;
ProfileData data;
String name;
public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
{
super(context, attrs);
......
......
}
public setCallBack( TaskCompleteListener<String> cb)
{
this.callback = cb;
}
//Heres where things get complicated
public void onClick(View v)
{
callback.onProfileClicked("Pass your result or any type");
}
}
And implement this to any Activity.
and call it like
ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
pv.setCallBack(new TaskCompleteListener
{
public void onProfileClicked(String resultStringFromProfileView){}
});
Context may be an Application, a Service, an Activity, and more.
Normally the context of Views in an Activity is the Activity itself so you may think you can just cast this Context to Activity but actually you can't always do it, because the context can also be a ContextThemeWrapper in this case.
ContextThemeWrapper is used heavily in the recent versions of AppCompat and Android (thanks to the android:theme attribute in layouts) so I would personally never perform this cast.
So short answer is: you can't reliably retrieve an Activity from a Context in a View. Pass the Activity to the view by calling a method on it which takes the Activity as parameter.
Never ever use getApplicationContext() with views.
It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.
I used convert Activity
Activity activity = (Activity) context;
For kotlin user -
val activity = context as Activity
an Activity is a specialization of Context so, if you have a Context you already know which activity you intend to use and can simply cast a into c; where a is an Activity and c is a Context.
Activity a = (Activity) c;
This method should be helpful..!
public Activity getActivityByContext(Context context){
if(context == null){
return null;
}
else if((context instanceof ContextWrapper) && (context instanceof Activity)){
return (Activity) context;
}
else if(context instanceof ContextWrapper){
return getActivity(((ContextWrapper) context).getBaseContext());
}
return null;
}
I hope this helps.. Merry coding!
how about some live data callback,
class ProfileView{
private val _profileViewClicked = MutableLiveData<ProfileView>()
val profileViewClicked: LiveData<ProfileView> = _profileViewClicked
}
class ProfileActivity{
override fun onCreateView(...){
profileViewClicked.observe(viewLifecycleOwner, Observer {
activityMethod()
})
}
}
Create an extension function. And call this extension function with your context like context.getActivity().
fun Context.getActivity(): AppCompatActivity? {
var currentContext = this
while (currentContext is ContextWrapper) {
if (currentContext is AppCompatActivity) {
return currentContext
}
currentContext = currentContext.baseContext
}
return null
}
Kotlin android shorthand extension version of Theo's solution
private fun Context?.getParentActivity() : AppCompatActivity? = when {
this is ContextWrapper -> if (this is AppCompatActivity) this else this.baseContext.getParentActivity()
else -> null
}
Usage of above explained here
I've got one question regarding the intent action ACTION_CALL.
What is the correct way of getting back to the own application/activity after the user ends the call?
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +m1));
startActivity(intent);
I have made the call using the above code. Please provide me with a solution to call my own activity after the call action.
unfortunately some phones have settings to force going into for example the Call Log after a call...
However, you can run a loop after your startActivity to check TelephonyManager.getCallState, and when it's again TelephonyManager.CALL_STATE_IDLE, you can restart your own Activity
be sure to add some sleep to the loop
AFter the endofcall.......it just had to come back to the activity..!! you can handle that one onRestart();
I run with the same problem, and ended up solving it like this:
Make a Callback interface with single (or multiple if you want)
methods
Implement that interface in your activity
Make a reference to that interface inside PhoneStateListener class
Call a method within that interface when the call ended
public class CallTracker extends PhoneStateListener implements Runnable {
private Context mActivity;
private Callback mCallback;
public interface Callback {
void onCallEnded();
}
public CallTracker(Activity activity) {
super();
mActivity = activity;
if (mActivity instanceof Callback) {
mCallback = (Callback) mActivity;
}
}
#Override public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_IDLE) {
mCallback.onCallEnded();
}
}
public class CallerActivity extends AppCompatActivity implements
CallTracker.Callback {
#Override public void onCallEnded() {
Toast.makeText(this, "Call ended!", Toast.LENGTH_SHORT).show();
}
}