How to get a string result in AsyncTask android - android

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.

Related

Android - AsyncTask inside Fragment doesn't work in Marshmallow

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
}
}
}
}
}

get value from asynctask

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");
}
}

Android JSoup with AsyncTask - can't see the content

I use this code inorder to get the content of some website.
the textview stay empty. What I am doing wrong?
I added the jar into librires and also add internet permission to manifest.
public class MainActivity extends Activity {
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
}
public void onclick(View v) {
mt = new MyTask();
mt.execute(URL);
}
class MyTask extends AsyncTask<String, Void, String> {
Document doc;
String title=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
#Override
protected String doInBackground(String... params) {
try {
TimeUnit.SECONDS.sleep(2);
// doc = Jsoup.connect(params[0]).get();
// String title = doc.title();
doc = Jsoup.connect("http://www.example.com/").get();
Element content = doc.select("a").first();
title = content.text();
Log.d("AsyncTask doInBackground","URL: " + params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvInfo.setText(title);
}
}
}
I also not understand excaly when each method here is called
THANKS A LOT!
EDIT - the code after what was suggested in answer. Still not working:
public class MainActivity extends Activity implements OnClickListener{
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
tvInfo.setOnClickListener(this);
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String title = "hh";
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
}
catch (IOException e) {
e.printStackTrace();
}
return title;
}
#Override
protected void onPostExecute(String result) {
tvInfo.setText(result);
}
#Override
protected void onPreExecute() {
tvInfo.setText("Please wait");
}
}
#Override
public void onClick(View v) {
mt = new MyTask();
mt.execute(URL);
}
}
The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.
preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
}

Cannot show a ProgressDialog in AsyncTask

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();
}
}

app crashes when implementing async Android

I'm trying to implement async on Android but it keeps crashing my app, the code in doInBackground works if I put it in the oncreate so that i know that It works
any help is greatly appreciated
thanks
here's my code :
public class accueilEco extends Activity
{
String[] param = new String[5];
TextView nom;
TextView prenom;
ProgressDialog mDialog;
Context ctxt;
TelephonyManager tm;
connectEco ce;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nom = (TextView) findViewById(R.id.user);
ctxt = getBaseContext();
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
new chargerParam().execute();
}
public class chargerParam extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... params) {
try
{
ce =new connectEco();
param = ce.recupereParam(tm.getDeviceId());
if(String.valueOf(param[4]) == String.valueOf(1))
{
Toast.makeText(ctxt, "Paramétres chargées" , Toast.LENGTH_LONG).show();
//setContentView(R.layout.home);
nom.setText(param[1]+" "+ param[2]+" - "+param[3]);
}
else
{
Toast.makeText(ctxt, "=> login" , Toast.LENGTH_LONG).show();
}
}
catch(Exception ex)
{
Toast.makeText(ctxt, "erreur" , Toast.LENGTH_LONG).show();
}
return null;
}
}
}
You cannot access UI objects from another thread than the UI thread. The code:
nom.setText(param[1]+" "+ param[2]+" - "+param[3]);
will throw the exception.
You can access the UI elements when you are in onPreExecute() or onPostExecute(Result). Accessing UI elements while youre in doInBackground, it'll result in exception.
To "fix" this you need to read through and understand the AsyncTask implementation. Instead of declaring your background task by AsyncTask<Void, Void, Void> you can provide an "result type" that the can be posted from the doInBackground method to the onPostExecute method (on the UI thread). AsyncTask<Void, Void, String> (the String type).
You would have to do something like this:
#Override
protected void onPostExecute(String result) {
if (result != null)
nom.setText(result);
// else show toast
}
#Override
protected String doInBackground(Void... params) {
try {
String[] param = new connectEco().recupereParam(tm.getDeviceId());
if (String.valueOf(param[4]) == String.valueOf(1))
return param[1]+" "+ param[2]+" - "+param[3];
} catch(Exception ex) {
// ignore and return null
}
return null;
}

Categories

Resources