I have an AsyncTask class SearchForQuestions that is called from an Activity QuizMap. When looping through an array in SearchForQuestions I can't find the correct context for toast to appear within the AsynTask.
The standard Toast.makeText(getApplicationContext(), "This is Toast!!!", Toast.LENGTH_SHORT).show(); gives error getApplicationContext() undefined.
I have tried some of the solutions to this offerred by SO, most of them are listed here and concern getting UiThread and running on that.
I can't get this to work however. Here's example code snippets of what i have tried. I have put a method in QuizMap and try calling it from SearchForQuestions but SearchForQuestions isn't recognised. How can I get around this? )Still a newbie at java...)
// QuizMap activity
public class QuizMap extends FragmentActivity
implements OnMarkerClickListener {
private GoogleMap map;
private static final String TAG = "QuizMap"; // debugging
...
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizmap);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
...
}
// make toast inside AsyncTask
public void showNotNearToast(final String toast) {
QuizMap.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(QuizMap.this, "This is Toast!!!", Toast.LENGTH_SHORT).show();
}});
}
.
// SearchForQuestions class
private class SearchForQuestions extends AsyncTask<String, Void, DataHandler> {
// checks for proximity to question locations
Location location =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
#Override
protected DataHandler doInBackground(String... pointsList) {
String result = pointsList[0];
...
}
#Override
protected void onPostExecute(DataHandler result) {
ArrayList<String> resultsArray = result.results;
Integer numPoints = resultsArray.size();
for (int i =0;i<numPoints;i++){
String[] pointDetails = resultsArray.get(i).split("::");
...
// we can make use of the Android distanceTo function to calculate the distances
float distance = location.distanceTo(fixedLoc);
if (i > DIST) { // this is UCL
showNotNearToast("My Message"); // showNotNearToast undefined
if (distance < DIST) {
...
}
};
I'm going t close this question. I haven't solved my problem but the number of answers provided that apparently work in other situations suggest there's something else going on. I'm going to re-structure the classes to get around having to call from within AsyncTask.
Just Toast it, why do you want to create a function for it? onPostExecute() is already on UI thread.
You are not able to access because inner Class can not call functions of Outer class unless you pass instance of the outer class.
Call your toast in onPostExecute
Create an interface for a callback.
public interface ToastCallback {
public void invoke(String text);
}
Your AsyncTask constructor
private ToastCallback toastCallback;
public SearchQuestions(ToastCallback callback) {
this.toastCallback = callback;
}
// in doInBackground() {
toastCallback.invoke("Toast from background");
}
In Your Activity,
private void showNotNearToast(String text) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
}
public class MyToastCallback implements ToastCallback {
#Override
public void invoke(String text) {
showNotNearToast(text);
}
}
// Asynctask call
new SearchQuestion(new MyTosatCallback()).execute(<Your params here>);
Try this from inside your AsyncTask:
myActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
}
});
Where you have your
showNotNearToast("My Message"); // showNotNearToast undefined
Replace myActivity with the name of your Activity.
(Ab)use the publishProgress method
private class ToastAsyncTask extends AsyncTask<Void, String, Void>{
#Override
protected Void doInBackground(Void... voids) {
SystemClock.sleep(1000);
publishProgress("Toast msg string");
SystemClock.sleep(1000);
return null;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
}
}
**UPDATE: ** since you are having problems with context for some reason, use this version. Tough the implementation above works for me.
private class ToastAsyncTask extends AsyncTask<Void, String, Void> {
private WeakReference<Context> contextRef;
public ToastAsyncTask(Context context) {
contextRef = new WeakReference<Context>(context);
}
#Override
protected Void doInBackground(Void... voids) {
SystemClock.sleep(1000);
publishProgress("Toast msg string");
SystemClock.sleep(1000);
return null;
}
#Override
protected void onProgressUpdate(String... values) {
if (contextRef.get() != null) {
Toast.makeText(contextRef.get(), values[0], Toast.LENGTH_SHORT).show();
} else {
// The context was destroyed.. check what you are doing
}
}
}
Use it like this
new ToastAsyncTask(MainActivity.this).execute();
Pass the activity into the AsyncTask. See below.
private class SearchForQuestions extends AsyncTask<String, Void, DataHandler> {
Activity activity;
public void SearchForQuestions(Activity activity){
this.activity = activity;
}
//... rest of the code
public class QuizMap extends FragmentActivity implements OnMarkerClickListener {
/*...*/
new SearchForQuestions(this).execute();
/*...*/
/*When calling the toast:*/
Toast.makeText(this.activity, "This is Toast!!!", Toast.LENGTH_SHORT).show();
Related
MainActivity execute external asynctask class
Here my code
public class MainActivity extends AppCompatActivity implements View.OnClickListener
...
public void onFirstBtnClick()
{
AysncClass ac = new AyncClass();
ac.execute();
}
and external asynctask
public class AysncClass extends AsyncTask<String, String, Integer>
#Override
protected Integer doInBackground(String... strings) {
Method1(strings[0], Integer.parseInt(strings[1]));
return null;
}
public Method1(Strins s, int i)
{
onProgressUpdate("first start");
publishProgress();
// do more work
onProgressUpdate("second start");
publishProgress();
}
public void Method2()
{
onProgressUpdate("Method2 here");
publishProgress();
}
...
#Override
protected void onProgressUpdate(final String... values) {
super.onProgressUpdate(values);
// what can i do here?
}
}
I use runOnUiThread like this in onProgressUpdate
((MainActivity)context).runOnUiThread(new Runnable()
{
#Override
public void run()
{
((MainActivity)context).tvRead.append(values[0]);
}
});*
but It occur 'java.lang.ArrayIndexOutOfBoundsException: length=0; index=0' even though values[0] is not null.
Also I use interface
this.context.WriteText(values[0]);
It occur same error
And I do this...
((MainActivity)context).tvRead.append(values[0]);
It occur 'java.lang.RuntimeException: An error occured while executing doInBackground()' and 'CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.'
...How can I resolve?
Do not call onProgressUpdate(). Instead just call publishProgress("The String").
By calling publishProgress without a parameter you will have no values in onProgressUpdate. That's why you get an IndexOutOfBondException.
Don't call onProgressUpdate on your own.
Call publishProgress("My Message");
In onProgressUpdate, don't use runOnUIThread.
OnProgressUpdate runs on the Ui thread only.
Instead of this
onProgressUpdate("Method2 here");
publishProgress();
Do this
publishProgress("Method2 here");
On ProgressUpdate will be in UIThread, no need again specify in UI thread. From DoInbackGround you have to make call publishProgress method for invoking OnProgressUpdate.
Use an interface as communicator between your Activity and AsyncTask
Create Interface
interface MyInterface {
void callActivityUi(String progress); // use float maybe
}
Initialize AsyncTask like this:
AysncClass as = new AysncClass(new MyInterface() {
#Override
void callActivityUi (String progress) {
// you will receive data here
}
});
Create a constructor in your AysncClass
private MyInterface myInterface;
public AysncClass (MyInterface myInterface) {
this.myInterface = myInterface;
}
Call Activity in onProgressUpdate(String... values)
myInterface.callActivityUi(values[0]);
Based on your code, you can use an interface to post the progress to the activity. I modified your code like this:
AsyncTask class
public class AysncClass extends AsyncTask<String, String, Integer> {
public interface SomeListener {
public void onSomething(Object mObject);
}
private SomeListener sl;
public AysncClass(SomeListener sl) {
this.sl = sl;
}
#Override
protected Integer doInBackground(String... strings) {
Method1(strings[0], Integer.parseInt(strings[1]));
return null;
}
public Method1(Strins s, int i) {
onProgressUpdate("first start");
publishProgress();
// do more work
onProgressUpdate("second start");
publishProgress();
}
public void Method2() {
onProgressUpdate("Method2 here");
publishProgress();
}
...
#Override
protected void onProgressUpdate(final String... values) {
super.onProgressUpdate(values);
// what can i do here?
sl.onSomething(mObject);
}
}
MainActivity class
public class MainActivity extends AppCompatActivity implements View.OnClickListener,
AysncClass.SomeListener {
...
public void onFirstBtnClick() {
AysncClass ac = new AyncClass(this);
ac.execute();
}
#Override
public void onSomething(Object mObject) {
//Do your UI work here
}
}
Here is my problem. I have created a asyncTask to link to my database and send and receive information using JSON.
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
returnValues = dataParsed.split("\\s+");
mainActivity.getValue(this is the function that calls anotherfunction in
asyncTask)
Log.v("ARRAY LENGTH", String.valueOf(returnValues.length));
}
public String[] returnmyString(){
//return mySaveData;
Log.v("ARRAY LENGTH 2", String.valueOf(returnValues.length));
return returnValues;
}
I create the asyncTask object within my activity based class and then call that object.execute. My problem is that my code will continue to run once calling the object.execute and one of the lines calls a function within the asyncTask class before it is done executing all the code.
process.activitySave(1); //<---Process is the object for the asyncTask class
process.ContextSave(this,ServerURLSource,myParameters);
process.execute()
changedData = process.returnmyString(); //<-- this is the line of code that gets implemented that returns a null value
I have tried creating a Mainactivity object in the asyncTask class and then calling a function then that retrieves the value but my app crashes when I do this. any help would be appreciated. I would like to put some sort of listener in the mainactivity class as it seems I cannot reference any of the functions from my mainactivity class in my asyncTask class.
This is the function within the asyncTask to return the value:
public String[] returnmyString(){
//return mySaveData;
Log.v("ARRAY LENGTH", String.valueOf(returnValues.length));
return returnValues;
}
Method 1 is the basic, anonymous inner class implementation. Because of the inner AsyncTask class is not static class, you can access to the CustomActivity's properties from that implementation.
In Method 2, AsyncClass implemented separately. If you gave your activity to this class, it can be call back your desired method after execution. This method, for our example is the #setChangedData method. CustomAsyncTask call backs the #setChangedData in the #onPostExecute.
public class CustomActivity extends AppCompatActivity {
String mChangedData;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Method 1 - change data into the anonymously implemented AsyncTask class
new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
CustomActivity.this.mChangedData = "foo"; // this changes mChangedData as "foo"
}
}.execute(1);
// Method 2 - change data into the custom AsyncTask class
new CustomAsyncTask(this).execute(2);
}
public void setChangedData(String changedData){
this.mChangedData = changedData;
}
static class CustomAsyncTask extends AsyncTask<Integer, Void, Void> {
CustomActivity mActivity;
public CustomAsyncTask(CustomActivity activity) {
this.mActivity = activity;
}
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mActivity.setChangedData("bar");
}
}
}
And, as method 3, if you want to separate you Activity and AsyncTask more loosely, this is the handler method:
public class CustomActivity extends AppCompatActivity {
private String mChangedData;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomAsyncTask task = new CustomAsyncTask();
task.setOnDataChangedListener(new CustomAsyncTask.OnDataChangedListener() {
#Override
public void onDataChanged(String data) {
mChangedData = data;
}
});
task.execute(1);
}
private static class CustomAsyncTask extends AsyncTask<Integer, Void, Void> {
private OnDataChangedListener onDataChangedListener;
#Override
protected Void doInBackground(Integer... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(onDataChangedListener != null) {
onDataChangedListener.onDataChanged("foo");
}
}
void setOnDataChangedListener(OnDataChangedListener onDataChangedListener) {
this.onDataChangedListener = onDataChangedListener;
}
interface OnDataChangedListener {
void onDataChanged(String data);
}
}
}
I know this is a duplicate question but please hold on. I have read some similar questions and answer but none of them seems working for me.
What to do:
I have to do a search which will send a request to a web service and receive a response.
As i can't consume network on UI thread, I used AsyncTask.
What i tried:
I tried using task.execute() this returns immediately without even showing progressdialog box and i receive response as null (set in onPostExecute)
if i use task.execute.get() then it freezes screen and again no dialog box shows up (but i receive response correctly).
Below is my code with task.execute. Kindly correct me.
public class LookIn extends AppCompatActivity implements View.OnClickListener{
private Button btn=null;
private TextView txtPinCode=null;
private Service service=null;
private final static int timeout=20;
private String jsonResponse;
//private ProgressBar helperSearchProgressBar;
private String pincode="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_look_in);
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(this);
txtPinCode=(TextView) findViewById(R.id.txtPinCode);
this.service=(Service) ParamFactory.getParam(ConstantLabels.SELECTED_SERVICE_ID);
// this.helperSearchProgressBar=(ProgressBar)findViewById(R.id.helperSearchProgressBar);
}
#Override
public void onClick(View v) {
String pincode= txtPinCode.getText().toString();
if(pincode==null || pincode.isEmpty() || pincode.length()!=6)
{
this.txtPinCode.setError("Please enter a 6 degit pin code from 700000 to 700200");
return;
}
ParamFactory.setParam(ConstantLabels.PINCODE_ID,pincode);
this.pincode=pincode;
loadHelper();
Intent intent= new Intent(LookIn.this,SearchResult.class);
startActivity(intent);
}
public void setJsonResponse(String jsonResponse)
{
this.jsonResponse=jsonResponse;
}
private void loadHelper()
{
Log.v("Callme", "Running thread:" + Thread.currentThread().getId());
ArrayAdapter<User> adapter=null;
String params=this.pincode+","+this.service.getId();
List<User> result=null;
try {
new CallmeGetHelperAsyncTask().execute(params); //my task.execute()
result= RestUtil.getUserList(jsonResponse);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, result);
ParamFactory.setParam("getHelperForService", adapter);
}
catch(JSONException x)
{
Log.e("Callme", Log.getStackTraceString(x));
}
}
class CallmeGetHelperAsyncTask extends AsyncTask<String,Void,String > {
// private Context context=null;
private ProgressDialog dialog=null;
private String jsonResponse;
private LookIn activity;
public CallmeGetHelperAsyncTask(){}
public CallmeGetHelperAsyncTask(LookIn activity)
{
this.activity=activity;
}
#Override
protected void onPreExecute() {
this.dialog= new ProgressDialog(LookIn.this);
this.dialog.setMessage("Loading...");
this.dialog.show();
Log.v("Callme","Dialog Shown");
}
#Override
protected void onPostExecute(String s) {
if(s!=null)
{
this.activity.setJsonResponse(s);
}
else
{
Log.v("Callme","kill me");
}
if(this.dialog.isShowing())
{
Log.v("Callme","Closing Dialog");
this.dialog.dismiss();
}
}
#Override
protected String doInBackground(String... params) {
Log.v("Callme","From Background:"+Thread.currentThread().getId());
String pincode=params.clone()[0].split(",")[0];
String serviceId=params.clone()[0].split(",")[1];
String url=String.format(URL.GET_HELPER,serviceId,pincode);
jsonResponse= null;
try {
jsonResponse = RestUtil.makeRestRequest(url);
} catch (IOException e) {
e.printStackTrace();
}
return jsonResponse;
}
}
}
Note: I haven't tried using while loop to waiting for the asynctask, because i think that will also end up freezing my screen. Please correct me if i am wrong
I haven't tried using while loop to waiting for the asynctask
No need to use loop for waiting AsyncTask Result.
Because onPostExecute method execute after doInBackground so instead of using jsonResponse just after call of execute method, do it inside setJsonResponse method, because this method called from onPostExecute which always run on Main UI Thread:
public void setJsonResponse(String jsonResponse)
{
this.jsonResponse=jsonResponse;
//Create adapter object here
result= RestUtil.getUserList(jsonResponse);
adapter = new ArrayAdapter(...);
ParamFactory.setParam("getHelperForService", adapter);
}
*************PROBLEM FIXED, CHECK BELOW FOR A SOLUTION*************
I have been struggling with that nearly half a day. Cannot get it work properly.
I have AsyncTask with private method, so I can pass boolean and String values in CustomLvAdapter
private void changeJobStatus(final boolean isAppliedforAJob, final String jobID){
class ChangeJobStatus extends AsyncTask<Void,Void,String> {
//private Delegates del = null;
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
if(isAppliedforAJob) {
loading = ProgressDialog.show(context, "","Canceling application", false);
}
else {
loading = ProgressDialog.show(context, "","Applying for position", false);
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//del.asyncCompleteOnCustomJob(true);
loading.dismiss();
}
#Override
protected String doInBackground(Void... v) {
String res;
HashMap<String,String> params = new HashMap<>();
params.put(Config.KEY_USER_ID, studentID);
params.put(Config.KEY_JOB_ID, jobID);
RequestHandler rh = new RequestHandler();
if(isAppliedforAJob)
res = rh.sendPostRequest(Config.URL_CANCEL_APPLICATION, params);
else
res = rh.sendPostRequest(Config.URL_APPLY_FOR_A_JOB, params);
Log.d("Stringas", "CustomListViewBackground " + res);
return res;
}
}
ChangeJobStatus cjs = new ChangeJobStatus();
cjs.execute();
}
and in onPostExcecute() I want to call notifyOnDataSetChanged() to my another activity lvAdapters.
As far as I read I have to implement delegate interface, but I didnt succeed doing that. I fail at initializing delegate in my main class, because changeJobStatus method is private and it is called in customLvAdapter class.
If I make a constructor in ChangeJobStatus class
public ChangeJobStatus(Delegates delegate)
{
this.del = delegate;
}
I have to pass something in the parameters, when excecuting it. If I pass new Delegate, my delegate implementation, which is in my another activity is not triggered.
ChangeJobStatus cjs = new ChangeJobStatus(new Delegates() {
#Override
public void asyncCompleteOnCustomJob(boolean success) {
//whatever
}
});
cjs.execute();
I hope you can help me figure out right implementation for that,
Cheers
***********SOLUTION***********
Sadly, I couldn't implement what fellow user gave to me, but I am very glad that I heard from one of you I can use broadcast receiver. And it worked.
This is what I did
Create a Broadcast Receiver in your main class
private final BroadcastReceiver broadcastJobList = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//what will happen, when event triggers
}
};
Register custom intent and register it to Broadcast receiver in your main class onCreate method or wherever you feel comfortable :)
IntentFilter filter = new IntentFilter();
filter.addAction("jobListChanged");
registerReceiver(broadcastJobList, filter);
All we left to do is send intent which will trigger Broadcast receiver. Following code in my scenario went to onPostExcecute method in custom adapter (context was initialized for Context at the beggining of custom adapter)
Intent intent = new Intent();
intent.setAction("jobListChanged");
context.sendBroadcast(intent);
Hope I will help anyone that has this problem. Cheers!
// your asynctask class
public class ChangeJobStatus extends AsyncTask<String, Void, String> {
private ProgressDialog loading;
private OnResponseListener responseListener;
private boolean isAppliedforAJob;
private Context con;
public ChangeJobStatus(Context con,boolean state) {
super();
// TODO Auto-generated constructor stub
this.con=con;
isAppliedforAJob = state;
}
public void setOnResponseListener(OnResponseListener onLoadMoreListener) {
this.responseListener = onLoadMoreListener;
}
public interface OnResponseListener {
public void onResponse(String responsecode);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isAppliedforAJob) {
loading = ProgressDialog.show(con, "", "Canceling application", false);
} else {
loading = ProgressDialog.show(con, "", "Applying for position", false);
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// del.asyncCompleteOnCustomJob(true);
loading.dismiss();
responseListener.onResponse(s);
}
#Override
protected String doInBackground(String... param) {
String res="";
HashMap<String, String> params = new HashMap<>();
params.put(Config.KEY_JOB_ID, param[0]);// job id
params.put(Config.KEY_USER_ID, param[1]);// student id
RequestHandler rh = new RequestHandler();
if (isAppliedforAJob)
res = rh.sendPostRequest(Config.URL_CANCEL_APPLICATION, params);
else
res = rh.sendPostRequest(Config.URL_APPLY_FOR_A_JOB, params);
return res;
}
}
in your activity class
public class MainActivity extends Activity implements OnResponseListener {
String jobId="1",studId="1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChangeJobStatus cbs=new ChangeJobStatus(this, true);
cbs.setOnResponseListener(this);
cbs.execute(jobId,studId);
}
#Override
public void onResponse(String responsecode) {
// TODO Auto-generated method stub
//here u can do ur stuff with the string
}
}
I try a Toast Message interface. If app not connection internet, I want show a Toast Message and I'm wanting java interfaces.
This is MotherActivity.java. This file implement ToastMessagges.ToastMessaggeCallback
public class MotherActivity extends ActionBarActivity implements ToastMessagges.ToastMessaggeCallback {
ToastMessagges toastMessagges;
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother);
toastMessagges = new ToastMessagges();
AppStarter();
}
private void AppStarter(){
boolean checkinternet = InternetControl.checkInternetConnection( getApplicationContext() );
if( checkinternet ) {
toastMessagges.show_toast_messagge();
}
else {
}
}
#Override
public void LongToastMessagge() {
Toast.makeText(getApplicationContext(), "Hello World", Toast.LENGTH_LONG).show();
}
}
This is my ToastMessagges.java file.
public class ToastMessagges {
ToastMessaggeCallback toastMessaggeCallback;
public void show_toast_messagge(){
toastMessaggeCallback.LongToastMessagge();
}
public static interface ToastMessaggeCallback {
public void LongToastMessagge();
}
}
When the start this app. I get NullPointerException error.
Caused by: java.lang.NullPointerException
at com.medyasef.bulenttirasnewapp.bulenttiras.functions.ToastMessagges.show_toast_messagge(ToastMessagges.java:22)
at com.medyasef.bulenttirasnewapp.bulenttiras.MotherActivity.AppStarter(MotherActivity.java:36)
at com.medyasef.bulenttirasnewapp.bulenttiras.MotherActivity.onCreate(MotherActivity.java:29)
ToastMessagges.java:22
toastMessaggeCallback.LongToastMessagge();
Sorry bad english.
Please help.
Thank you.
You haven't initialized you ToastMessaggeCallback toastMessaggeCallback.
To do this, write
ToastMessaggeCallback toastMessaggeCallback = new ToastMessaggeCallback(){
public void LongToastMessagge(){
// add some toasting code here
}
};
This will make an object implementing your interface (called "anonymous class"). Of course, your ToastMessaggeCallback should do something in the method LongToastMessagge, so add the desired code there.
I will recommend you to create a Util class instead of Interface. I'm here giving you an example of Util class.
public class Util {
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
Then call the showToast() method from your activity as follows...
Util.showToast(YourActivity.this, "text");
Update:
Declare your Interface as a individual, not inside a class as below...
public interface ToastMessaggeCallback {
public void showLongToastMessagge(String text);
}
Then implement the Interface as follows...
public class MotherActivity extends ActionBarActivity implements ToastMessaggeCallback {
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother);
AppStarter();
}
private void AppStarter(){
boolean checkinternet = InternetControl.checkInternetConnection( getApplicationContext() );
if( checkinternet ) {
showLongToastMessagge("Hello World");
}
else {
}
}
#Override
public void showLongToastMessagge(String text) {
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
}
Your ToastMessagges class needs to provide a method to register the callback. Then, your Activity needs to call this method to register itself as the callback, right after you construct the ToastMessages object.