how to call non static method from static method in android
19,647
Solution 1
public static void First_function(Context context)
{
SMS sms = new SMS();
sms.Second_function(context);
}
public void Second_function(Context context)
{
Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash
}
The only solution to achieve this is that you need to pass the current context as a parameter. I wrote the code for only Toast but you need to modify it as per your requirements.
pass the Context from the your activity First_function(getApplicationContext())
etc..
for static string
public static String staticString = "xyz";
public static String getStaticString()
{
return staticString;
}
String xyz = getStaticString();
Solution 2
You should have a reference to a Context. You are trying to get the application context from inside a SMS instance.
I guess you are calling the First_function from an Activity or Service. So you can do this:
Class SMS
{
public static void First_function(Context context)
{
SMS sms = new SMS();
sms.Second_function(context);
}
public void Second_function(Context context)
{
Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash
CallingCustomBaseAdapters(); //this was the adapter class and i anable to call this also
}
Then, from your activity:
SMS.First_function(this); //or this.getApplicationContext()
Comments
-
Vishnu almost 2 years
I am facing a big problem in calling non static method from static method.
This is my code
Class SMS { public static void First_function() { SMS sms = new SMS(); sms.Second_function(); } public void Second_function() { Toast.makeText(getApplicationContext(),"Hello",1).show(); // This i anable to display and cause crash CallingCustomBaseAdapters(); //this was the adapter class and i anable to call this also }
I am able to call Second_function but unable to get Toast and CallCustomBaseAdapter() method, crash occurs.
What should I do to fix that issue ?
-
Vishnu over 11 yearsCan u tell me how to have a reference?
-
aamit915 over 11 yearsHow is your code ANY better then the code that was originally written? SMS still has no reference to a context - it's just a class that doesn't extend activity. The original code was fine in the sense that non-static methods were not being called in a static context. Unfortunately, it seems Vishnu has no idea what's going on but that doesn't mean you just go along with it.
-
aamit915 over 11 yearsYou'll have to post all your code if you want any help from me. I'm sorry but unfortunately I cannot understand what you're trying to do :(
-
Vishnu over 11 yearsis it possible to move string value from static string to non static String?
-
Sebastian Breit over 11 yearslol ...stackoverflow users are funny sometimes.. the accepted answer is exactly the same as mine, but mine has one downvote.. excelent