This is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.list);
new GetBlockListAsyncTask().execute(BlockListActivity.this);
}
public void initializeDialog() {
dialog = ProgressDialog.show(BlockListActivity.this, "", "Loading data. Wait...", true);
dialog.show();
}
public void dismissDialog(){
dialog.dismiss();
}
The GetBlockListAsyncTask:
public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String>{
private BlockListActivity callerActivity;
private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";
#Override
protected String doInBackground(Object... params) {
callerActivity = (BlockListActivity)params[0];
try {
Log.d(TAG, "Start to sleep");
Thread.sleep(4000);
Log.d(TAG, "End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
callerActivity.dismissDialog();
}
#Override
protected void onPreExecute() {
callerActivity.initializeDialog();
}
}
It will show error:
'Caused by: java.lang.NullPointerException'
onPreExecute(GetBlockListAsyncTask.java:101)
I find a solution is that if I move the initializeDialog out of the AsyncTask and put it before the line new GetBlockListAsyncTask().execute(BlockListActivity.this); in onCreate, it works.
The question is how to make it work if I want to put the initializeDialog in the AsyncTask .
Try adding a public constructor to your AsyncTask that accepts the Activity Context as the first argument:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a new AsyncTask with the Activity Context
AsyncTask task = new GetBlockListAsyncTask(this);
// Execute the task
task.execute();
}
public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String> {
private Context activityContext;
private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";
//Constructor
public GetBlockListAsyncTask(Context c) {
// Store the activity context
activityContext = c;
}
#Override
protected String doInBackground(Object... params) {
try {
Log.d(TAG, "Start to sleep");
Thread.sleep(4000);
Log.d(TAG, "End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
activityContext.dismissDialog();
}
#Override
protected void onPreExecute() {
activityContext.initializeDialog();
}
}
Related
I created an AsyncTask to fetch scores. It shows the progressdialog for a split-sec and then disappears. The doInBackground method never gets executes. This task is called inside a fragment.
private class GetScore extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute() {
final ProgressDialog show = progressDialog.show(getActivity(), "", yourName);
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
scoreMap = ScoreCalc.getEngScore(yourName);
// Toast.makeText(LoveActivity.this, engageMap.toString(), Toast.LENGTH_SHORT).show();
return null;
}
#Override
protected void onPostExecute(String img) {
}
}
.
.
.
.
.
.
.
private void confirmYes() {
String s =mEditText.getText().toString();
if(s.equals(""))
return;
new GetScore().execute();
}
Help?
use this asynctask class instead of your class.
public class GetScore extends AsyncTask<String, Void, String>
{
String method;
#Override
protected String doInBackground(String... arg0)
{
method = arg0[0];
return getData.callWebService(arg0[0], arg0[1]);
}
protected void onPostExecute(String xmlResponse)
{
if(xmlResponse.equals("") )
{
try{
if(progDialog!=null && progDialog.isShowing()){
progDialog.dismiss();
}
}catch(Exception ex){}
Toast.
}
else
{
if (method.equals("methodname"))
{
MethodName(xmlResponse, "ResponseTag");
try{
if(progDialog!=null && progDialog.isShowing()){
progDialog.dismiss();
}
}catch(Exception ex){}
//What Ever Want to Do
}
}
}
}
}
I found many subject about but I can't get a solution, I'm doing a soap request in doInBackground method of asyncTask, and I want to get an Integer to know if the process is done, here I call my asyncTask:
Simulation.AsyncSoapCall task = new Simulation.AsyncSoapCall();
try {
Integer taskResult = task.execute().get();
} catch (Exception e) {
e.printStackTrace();
}
My AsyncTask class:
private class AsyncSoapCall extends AsyncTask<Void, Void, Integer> {
Integer result;
Boolean isInternetPresent = false;
Boolean isUrlAvailable = false;
ConnectionDetector cd;
AsyncSoapCall(){
}
#Override
protected Integer doInBackground(Void... params) {
cd = new ConnectionDetector(getActivity().getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
String namespace = getResources().getString(R.string.NAMESPACE);
String url = getResources().getString(R.string.URL);
String soapaction = getResources().getString(R.string.SOAP_ACTION);
String login = getResources().getString(R.string.login);
String mdp = getResources().getString(R.string.mdp);
isUrlAvailable = cd.isUrlAvailable();
// check for Internet status
if (isUrlAvailable) {
String idApplication = Installation.id(getActivity());
SOAPContact soapContact = new SOAPContact(namespace, url, soapaction, login, mdp);
soapContact.saveParams(getResources().getString(R.string.origine), db);
result = 1;
} else {
result = 2;
}
} else {
result = 3;
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
I don't get error my app crasha at this line:
Integer taskResult = task.execute().get();
try to get the value from onPostExecute like
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
int yourNum = result;
}
that's it
Did you read the doc?
https://developer.android.com/reference/android/os/AsyncTask.html
AsyncTask has no "get" method.
You need to define a OnPostExecute method which will be called when your task is over with your Integer as a parameter.
public class MyActivity extends Activity
{
private Integer myInteger;
private void blabla(){
Simulation.AsyncSoapCall task = new Simulation.AsyncSoapCall() {
#Override
protected void onPostExecute(Integer result) {
//... Your code here ...
MyActivity.this.myInteger = result;
MyActivity.this.myMethod(result);
}
}
try {
task.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void myMethod(Integer integer){
}
}
Here is one method with the help of interfaces,
MainActivity.java
public class MainActivity extends AppCompatActivity {
static String TAG=MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncSoapCall request = new AsyncSoapCall(new AsyncSoapCall.AsyncSoapInterface() {
#Override
public void callBack(String callBackValue) {
Log.d(TAG,callBackValue);
}
});
request.execute();
}
}
AsyncSoapCall.java
public class AsyncSoapCall extends AsyncTask<Void,Void,Void> {
interface AsyncSoapInterface{
void callBack(String callBackValue);
}
AsyncSoapInterface callbackObj;
AsyncSoapCall(AsyncSoapInterface callbackObj)
{
callbackObj = callbackObj;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
callbackObj.callBack("Your value");
}
}
I have a class AsyncCallWS that get content from webservice. It worked well. However, I want to get result in the class AsyncCallWS, namely returnServer string in the MainActivity . Could you help me to solve it?
public class MainActivity extends Activity {
String resultRegister;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnRegister =(Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
new AsyncCallWS().execute("123");
Log.d("DDD",resultRegister);
if(resultRegister.equals("")) {
Log.d("D", "OK");
}
else
{
Log.d("E", "False");
}
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
Log.i(TAG, "doInBackground");
String id_num = params[0];
//toast(id);
String url_registerID="server path"+id_num ;
try {
String returnServer=getStringContent(id);
Log.d("D",returnServer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
Remove 3rd parameter Void from this AsyncTask<String, Void, Void>
and replace it with String, i.e;
private class AsyncCallWS extends AsyncTask<String, Void, String>
After changing you'll get compilation errors in your doInBackground().. just change the return type from Void to String
protected String doInBackground(String... params)
Now you can get the String returned by this method in onPostExecute(String result)
The String result here is the String which is returned by doInBackground()
*EDIT *
public class MainActivity extends Activity {
String resultInActivity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncCallWS().execute("123");
//How to get respond from AsyncCallWS
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected String doInBackground(String... params) {
Log.i(TAG, "doInBackground");
String id_num = params[0];
//toast(id);
String url_registerID="server path"+id_num ;
try {
String returnServer=getStringContent(id);
Log.d("D",returnServer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnServer;
}
#Override
protected void onPostExecute(String result) {
Log.i(TAG, "onPostExecute");
resultInActivity = result;
if(resultRegister.equals("")) {
Log.d("D", "OK");
}
else
{
Log.d("E", "False");
}
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
} // Asyntask ends
} // activity ends
The response from AsyncTask is produced in onPostExecute() from there you can perform tasks based on the response etc.
I highly recommend you read the AsyncTask Life Cycle
private class AsyncCallWS extends AsyncTask
Replace the third parameter with String which results doInBackground return String and corresponding postExecute method parameter as String
protected String doInBackground(String... params)
protected void onPostExecute(String result)
In Order to get it on MainActivity you have to do the following Steps
Create an Interface anywhere you want to and declare a method of any name which should have parameter of type String
interface ResponseHandler
{
void onResponse(String result)
}
In the MainActivity you have to implement that interface and you will
get the data here in this method
ResponseHandler handler = new ResponseHandler(){
#override
public void onResponse(String result)
{
// enter code here
}
};
After implementing this interface you can provide the instance of it to the AsyncTask constructor.
AsyncTask task = new AsyncTask(handler);
You will get the reference of ResponseHandler in AsyncTask
public AsyncTaskClass(ResponseHandler handler)
{
this.handler = handler
}
//enter code here
void onPostExecute(String result)
{
handler.onResponse(result)
}
This way you will get the result in your MainActivity.
I'm calling async tasks in a loop on the onPostExecute() of an asyncTask. I want the control to wait until response of all the tasks is not receieved cause I'm collecting the response in a single arrayList which i have to pass a callback method after all the asyncTasks called in the loop are finished.
I'm avoiding to use the AsyncTask.get() as it blocks the main thread.
public class CallServerAsync extends AsyncTask<AsyncHttpRequestBo, Void, ArrayList<ArrayList<AsyncHttpRequestBo>>> implements PlatwareResponseListener {
PlatwareClientCommonUtils clientCommonFunctions;
Context context;
String url;
PlatwareResponseListener listener;
private ProgressDialog progressDialog;
ArrayList<AsyncHttpResponseBo> processResponseList = null;
ArrayList<AsyncHttpResponseBo> responseList = null;
public CallServerAsync(Context context, PlatwareResponseListener listener) {
this.context = context;
clientCommonFunctions = new PlatwareClientCommonUtils(context);
url = clientCommonFunctions.getServerUrlPrimary();
this.listener = listener;
responseList = new ArrayList<AsyncHttpResponseBo>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(context, "Please wait", "Downloading...");
}
#Override
protected ArrayList<ArrayList<AsyncHttpRequestBo>> doInBackground(AsyncHttpRequestBo... params) {
ArrayList<ArrayList<AsyncHttpRequestBo>> requestLists = clientCommonFunctions.generateRequestList(params);
return requestLists;
}
#Override
protected void onPostExecute(ArrayList<ArrayList<AsyncHttpRequestBo>> result) {
for (ArrayList<AsyncHttpRequestBo> httpRequestList : result) {
CallserverSubAsync callserverSubAsync = new CallserverSubAsync(context, this);
callserverSubAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, httpRequestList);
// ArrayList<AsyncHttpResponseBo> processResponseList = null;
// try {
// processResponseList = callserverSubAsync.get();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
}
listener.onAsyncTaskCompleted(responseList, listener);
progressDialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
progressDialog.dismiss();
super.onCancelled();
}
#Override
public void onAsyncTaskCompleted(ArrayList<AsyncHttpResponseBo> responseList, PlatwareResponseListener listener) {
if (listener instanceof CallServerAsync) {
processResponseList = responseList;
for (AsyncHttpResponseBo responseBo : processResponseList) {
this.responseList.add(responseBo);
}
}
}
public class Feedback extends ActivityGroup {
protected static LocalActivityManager mLocalActivityManager;
private EditText fd=null;
private Button send=null;
public int res_flag=0;
public String result="";
public String url="";
private RelativeLayout newaccount;
private TextView needhelp=null;
private String currentDateandTime="";
private boolean isonline;
protected String fd_text="";
public void replaceContentView(String id, Intent newIntent) {
View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView(); this.setContentView(view);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback);
initialization();
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
currentDateandTime = sdf.format(new Date());
}catch (Exception e) {
System.out.println(e);
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Feedback.Retrieve().execute();
}
});
}
private void initialization()
{
fd=(EditText)findViewById(R.id.fd);
send=(Button)findViewById(R.id.send);
}
class Retrieve extends AsyncTask<Void, Integer, Integer> {
ProgressDialog pd = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(Feedback.this);
pd.setMessage("Please wait while sending feedback..");
pd.setCancelable(false);
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
try{
System.out.println("IN BKGRND");
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
url="url"+fd_text.toString().trim()+"&datetime="+currentDateandTime;
url=url.replace(" ","%20");
url=url.replace("+","%2B");
System.out.println(url);
JSONObject json = JSONfunctions.getJSONfromURL(url);
JSONObject response1=json.getJSONObject("response");
result=response1.getString("Success").toString().trim();
System.out.println(result);
if(result.equalsIgnoreCase("1"))
{
System.out.println("Logged In");
res_flag=1;
}
else
{
System.out.println("failed");
res_flag=5;
}
}
catch (JSONException e) {
System.out.println(e);
}catch (Exception e) {
System.out.println(e);
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
}
Error is:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#40e16110 is not valid; is your activity running?
PROBLEM
I calling activity through another tabhost.,It loading only the view .The webservice and button are not working ., When i click the buttons it shows above error.Help me to proceed guys..
Reference:
http://www.gamma-point.com/content/android-how-have-multiple-activities-under-single-tab-tabactivity
NOw the ActivityGroup is deprecated.., What should i use now..
For what you have posted, it doesn't seem like you need to use ActivityGroup at all. Simply extend your Feedback from Activity class. For example:
public class Feedback extends Activity