I'm trying to get a response back from my public class saveData extends AsyncTask.
I added a public interface but the Android Studio gives me an error for the #Overide on my onCreate in the activity.
public class almostFinish extends Activity implements OnTaskCompleted{
#Override // here I get an Error
protected void onCreate(Bundle savedInstanceState) {}
#Override
public void onTaskCompleted(boolean result) {
//ToDo
}
}
My interface.
public interface OnTaskCompleted {
void onTaskCompleted(boolean isSuccess);
}
My AsyncTask class
public class saveData extends AsyncTask<List<String>, Void, Void> {
private OnTaskCompleted listener;
boolean myflag = false;
#Override
public void onPreExecute() {}
#Override
protected Void doInBackground(List<String>... params) { }
#Override
public void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompleted(myflag);
}
}
Thanks for any help.
I'm just getting an Error in the editor: "Annotations are not allowed here"
If I remove the #Override then I get an Error telling me to add #Override.
According this code you will get null pointer exception. because you have not assign the listener in code.
public class saveData extends AsyncTask < List < String > , Void, Void > {
private OnTaskCompleted listener;
boolean myflag = false;
#Override
public void onPreExecute() {}
#Override
protected Void doInBackground(List < String > ...params) {}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
onTaskCompleted(myflag);
}
}
Related
I have troubles on calling the method update from MainActivity class in a the MSG0100 non-activity class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void update(boolean msg100Preselection){
if(msg100Preselection){
mExpandableListViewAdapter.setSelectedChild(-1);
mExpandableListViewAdapter.notifyDataSetChanged();
}
}
}
And this is my class where i want to call the update method of Mainactivity.
public class MSG0100{
boolean msg100Preselection=false;
pulic void onUpdate(){
msg100Preselection=true;
// Want to call my update method here
MainActivity activity= new MainActivity();
activity.update(msg100Preselection); //<-------- Using mainactiviy object crashes my app.
}
}
What you want is impossible as you dont have a pointer to your main activity.
The following statement is invalid.
MainActivity activity= new MainActivity();
You are not allowed to use the new operator to create an activity. That should be done using an intent.
There are several things you could do:
Move your update method in another class
OR
declare your update method as static and use it like this:
MainActivity.update(msg100Preselection);
Try using a callbackListener :-
In your MSG0100 class
public class MSG0100 {
boolean msg100Preselection = false;
private static OnUpdateListener mListener;
public static setListener(OnUpdateListener mListener) {
this.mListener = mListener;
}
public void onUpdate() {
msg100Preselection = true;
if (mListener != null)
mListener.onUpdate(msg100Preselection);
}
public interface OnUpdateListener()
{
void onUpdate ( boolean msg100Preselection);
}
}
In your MainActivity-
public class MainActivity extends AppCompatActivity, OnUpdateListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MSG0100.setListener(this)
}
#Override
public void onUpdate(boolean msg100Preselection) {
if (msg100Preselection) {
mExpandableListViewAdapter.setSelectedChild(-1);
mExpandableListViewAdapter.notifyDataSetChanged();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
MSG0100.setListener(null)
}
}
This way you won't have any memory leaks or crashes due to Activity being killed.
In my Android app I have two activities :
1) MapsActivity
2) OtherActivity
MapsActivity has navigation drawer through which I opened OtherActivity . Now , I want to call a method (like updatemap() ) from MapsActivity .
After searching a lot on google I found this question on stackoverflow
How to call method in main activity from other activity? but that doesn't solves my problem .
UPDATE :
Here is the code for OtherActivity :
public class OtherActivity extends AppCompatActivity {
#Override
protected void attachBaseContext(Context newBase) {.....}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.... }
#Override
protected void onStart() {
super.onStart();
removeConnection(userID)
.... }
private void removeConnection(String currentUserId) {
...
// Here I want to call a function from MapsActivity i.e. disaplayLocation()
}
public static class ConnectedViewHolder extends
RecyclerView.ViewHolder{ ... }
}
Code for MapsActivity is :
public class MapsActivity extends AppCompatActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
#Override
protected void attachBaseContext(Context newBase) { ... }
#Override
protected void onCreate(Bundle savedInstanceState) { ... }
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull
String[] permissions, #NonNull int[] grantResults) { ... }
private void setUpLocation() { ... }
public void displayLocation() { ... } // This is the function i want to call
private void createLocationRequest() { ... }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { ... }
protected synchronized void buildGoogleApiClient() { ... }
private boolean checkPlayServices() { ... }
private void requestRuntimePermission() { ... }
private void startLocationUpdates() { ... }
#Override
public void onMapReady(GoogleMap googleMap) { ... }
#Override
public void onConnected(#Nullable Bundle bundle) { ... }
#Override
public void onConnectionSuspended(int i) { ... }
#Override
public void onConnectionFailed(#NonNull ConnectionResult
connectionResult) { ... }
#Override
public void onLocationChanged(Location location) { ... }
#Override
public boolean onCreateOptionsMenu(Menu menu) { ... }
#Override
public boolean onOptionsItemSelected(MenuItem item) { ... }
private void makeConnectionToGetLocation() { ... }
private void updateConnectedLatLng() { ... }
}
I am pasting only structure of code because it is 1000 line of code and pasting here is of no use and become more complicate to read .
I tried to add static keyword before displayLocation method but it gives error in variables within function and making every variable to global is not possible .
If MapsActivity is expecting a result from OtherActivity, you're better off with Getting Result From an Activity. Simply call OtherActivity via startActivityForResult() (instead of startActivity()):
static final int MAP_REQUEST = 1; // your request code
...
private void callOtherActivity() {
Intent intent = new Intent(this, OtherActivity.class)
startActivityForResult(intent, MAP_REQUEST);
}
Then in your MapsActivity, do this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MAP_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
updateMap();
}
}
}
Make a static function in one Activity like
public static double getVariance(double[] data)
{
double mean = getMean(data);
double temp = 0;
for(double a :data)
temp += (mean-a)*(mean-a);
return temp/data.length;
}
Then in another activity call it as:
double res = Activity1.getVariance(<your data>);
Hope it helps.
Be aware, you may get NullObjectRefernce if the other activity is closed.
to do it you can use public static method. so, you can call it from anywhere in the application.
in your activity add it.
public static void YOUR_NAME(){}
to call it in second activity add it.
try{
YOUR_ACTIVITY.YOUR_NAME();
}catch(Exception e){}
another solution, you can use EventBus library
https://github.com/greenrobot/EventBus
I cannot call method from another activity in OnNotificationPosted. I also tried to make instance of activity but failed. I searched alot but no success. please help
NotificationListener
public class NotificationListener extends NotificationListenerService {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
otherActivity oth = new otherActivity();
oth.loc();
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg", "Notification Removed");
}
}
otherActivity
public class OtherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
}
public void loc() {
//code body
}
}
public class OtherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
}
public static void loc(){
//code body
}
}
how to using : otherActivity.loc();
public class NotificationListener extends NotificationListenerService {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
otherActivity.loc();
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
I have a class that is used for various ASyncTasks. Sometimes, I need to hide certain buttons, or views or whatever based upon the Activity or action. The object needing visibility set can vary.
MyAsyncTask
public class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
private ProgressBar mProgressBar;
public ASynceResponse delegate = null;
public MyAsyncTask() {
this.delegate = delegate;
this.mProgressBar = progressBar;
}
#Override
protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected JSONObject doInBackground(String... params) {
return;
}
#Override
protected void onPostExecute(JSONObject data) {
mProgressBar.setVisibility(View.GONE);
delegate.processResults(data);
}
public interface ASyncResponse {
void processResults(JSONObject data);
}
}
I usually call it by:
new MyAsyncTask(this, mProgressBar).execute("Something","Something Else",null);
Which I pass in a ProgressBar in the Activity that shows the background action is happening.
But I want more. I want to Overide my classes onPreExecute and onPostExecute to hide/show other items too.
Is that possible?
But I am trying to find a way to Overide the onPreExecute to hide anytype (or many types) views.
Is something like this possible?
MyAsyncTask myAsyncTask = new MyAsyncTask(new onPreExecute(
// hide a view
));
You can do that using interface.
public class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
private ProgressBar mProgressBar;
public ASynceResponse delegate = null;
public MyAsyncTask() {
this.delegate = delegate;
this.mProgressBar = progressBar;
}
#Override
protected void onPreExecute() {
delegate.myOnPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected JSONObject doInBackground(String... params) {
return;
}
#Override
protected void onPostExecute(JSONObject data) {
mProgressBar.setVisibility(View.GONE);
delegate.processResults(data);
}
public interface ASyncResponse {
void processResults(JSONObject data);
void myOnPreExecute();
}
}
Demo class example
class Demo implements ASyncResponse{
.....
void processResults(JSONObject data){
....
}
void myOnPreExecute(){
// do your stuff for pre execute
}
}
I'm trying to do the simple act of hiding/showing ProgressBar according to AsyncTask state ,
I have two classes one extends FragmentActivity and second AsyncTask.
MainActivity.java
public class MainActivity extends FragmentActivity {
public static ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
}
#Override
protected void onStart() {
super.onStart();
// What will happen to the progress bar here?
}
#Override
protected void onStop() {
super.onStop();
// What will happen to the progress bar here?
}
#Override
protected void onResume() {
super.onResume();
// What will happen to the progress bar here?
}
}
MyAsyncTask.java
public class MyAsyncTask extends AsyncTask<Void,Void, Void> {
#Override
protected Void doInBackground() {
// start download some images from cloud
// Here the progress bar should start to appear in MainActivity
// mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
Log.d(TAG, "Finished book downloading images the cloud");
// Here the progress bar should start to disappear in MainActivity
// mProgressBar.setVisibility(View.GONE);
}
}
main_activity.xml
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
Hope you understand me, thank to everyone who can help.
The progress bar should appear in onPreExecute() method (still in UI thread). Then you dismiss it when you get back to UI thread in onPostExecute method.
public class MyAsyncTask extends AsyncTask<Void,Void, Void> {
#Override
protected void onPreExecute(Void result) {
Log.d(TAG, "Finished book downloading images the cloud");
// Here the progress bar should start to disappear in MainActivity
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground() {
// start download some images from cloud
// there is a time cost operation
}
#Override
protected void onPostExecute(Void result) {
Log.d(TAG, "Finished book downloading images the cloud");
// Here the progress bar should start to disappear in MainActivity
// mProgressBar.setVisibility(View.GONE);
}
}
You should use onPreExecute() method to show the dialog.
Here is MainActivity
#Override
protected void onResume() {
super.onResume();
new MyAsyncTask().execute();
}
I think you should read APIs first.
Use preExecute and postExecute methods as they run on UI thread.
public class MyAsyncTask extends AsyncTask<Void,Void, Void> {
ProgressBar pBar;
#Override
protected void onPreExecute(Void result) {
pBar=new ProgressBar(getContext());
pBar.show();
}
#Override
protected void onPostExecute(Void result) {
if(pBar !=null and pBar.isShowing()){
pBar.dismiss();
}
}
}
Use interface in Asyntask class for communicate with Activity class
public class MyAsyncTask extends AsyncTask<Void,Void,Void> {
//use context for activity reference
private Context context_;
public MyAsyncTask(Context context) {
this.context_=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(mCallBack!=null ){
mCallBack.onSuccess("Success");
}else {
mCallBack.onError("Error");
}
}
MyAsyncCallBack mCallBack=null;
public MyAsyncCallBack getmCallBack() {
return mCallBack;
}
public void setmCallBack(MyAsyncCallBack mCallBack) {
this.mCallBack = mCallBack;
}
public interface MyAsyncCallBack{
public void onSuccess(String successMessage);
public void onError(String successMessage);
}
}
Call AsynckTask Class from activity class.Before calling asyntask start progress. and after completing work in asyntask return activity via interface and hide progress.
startProgress();
MyAsyncTask mTask=new MyAsyncTask(YourActivity.this);
mTask.setmCallBack(new MyAsyncTask.MyAsyncCallBack() {
#Override
public void onSuccess(String successMessage) {
//do success work and hide progress
hideProgress();
}
#Override
public void onError(String successMessage) {
//do error work and hide progress
hideProgress();
}
});
mTask.execute();