I am calling a webservice using doInBackgroung methode in a service using this code
public class LoginService {
public int status;
private String _login;
private String _pass;
public HttpResponse response;
public LoginService(String log, String pass) {
_login = log;
_pass= pass;
authenticate();
}
private void authenticate() {
new RequestTask().execute("http://safedrive.url.ph/v1/login?email="+_login+"&password="+_pass);
}class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
Log.e("Login","******Login Started************");
HttpClient httpclient = new DefaultHttpClient();
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
status = statusLine.getStatusCode();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("reponse", responseString);
return responseString;
}
#Override
protected void onPostExecute(String responseString) {
Log.e("status",""+ status);
//when i execute my code with right values of password and address,status gets the right value (200) and i can loggout it
super.onPostExecute(responseString);
}
Then I call the service in my main activity after a click button
connectButton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
address = ADDRESS.getText().toString();
pwd = PASS.getText().toString();
LoginService logService = new LoginService(address,pwd);
Log.e("service", logService.getStatus()+"");// here the value of logService.getStatus() is 0 !!
if (logService.getStatus()==200 )
{
Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
startActivity(intent);
}
else {Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_LONG).show();}
}
});
The value of status is not changed in the main activity so I can't pass to the other activity.
You could start your AsyncTask in your Activity and go to the other Activity from onPostExecute
Anyways leave that comment as you said service I thought your using AsyncTask inside android's Service.
First Create an interface in your project for listening finish of your service
LoginServiceListener.java
public class LoginService {
public int status;
public HttpResponse response;
private String _login;
private String _pass;
private LoginServiceListener mListener = null;
// Update your constructor
public LoginService(String log, String pass, LoginServiceListener iListener) {
_login = log;
_pass = pass;
mListener = iListener;
authenticate();
}
private void authenticate() {
new RequestTask().execute("http://safedrive.url.ph/v1/login?email=" + _login + "&password=" + _pass);
}
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
Log.e("Login", "******Login Started************");
HttpClient httpclient = new DefaultHttpClient();
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
status = statusLine.getStatusCode();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("reponse", responseString);
return responseString;
}
#Override
protected void onPostExecute(String responseString) {
Log.e("status", "" + status);
// On service completion you result will be posted back to the activity
mListener.loginFinished(responseString);
}
}
}
Make your activity to register with LoginServiceListener to listen for the service completion events by implementing interface LoginServiceListener
Make your service call as :
LoginService service = new LoginService("user", "pass", this);
This will ask you to implement the interface LoginServiceListener and hence add the method
#Override
public void loginFinished(String iResponse)
{
// This is you response. Now do whatever you want to do.
}
Related
I have a method name Request() in the onCreate method of the activity.
private void Request() {
new PostDataAsyncTask(textEmail, tValue).execute();
}
Iam passing two strings in it and the async class is as follows:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
public PostDataAsyncTask(String textEmail, String hello) {
data = textEmail;
data1= hello;
}
long date = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
String dateString = simpleDateFormat.format(Long.valueOf(date));
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
}
private void postText(){
try{
String postReceiverUrl = "http://techcube.pk/game/game.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", data));
nameValuePairs.add(new BasicNameValuePair("score", data1));
nameValuePairs.add(new BasicNameValuePair("datetime", dateString));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("SuccesS", "Response: " + responseStr);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now what i want is that i want to get the value of responseStr in my MainActivity that is generated when posttext method called.
How to show this responseStr value in the MainActivity?
Remember there is a new class that i made named as PostDataAsyncTask so how to access responseStr from this class and show it in my mainActivity as a Toast or Textview?
Please Help
You can create an interface that you pass into the method in question. For example
public interface INetworkResponse {
void onResponse(String response);
void onError(Exception e);
}
You would then need to create a concrete implementation of the interface. perhaps as a child class inside the activity that calls the AsyncTask.
public class MyActivity extends Activity {
private void Request() {
NetworkResponse response = new NetworkResponse();
new PostDataAsyncTask(textEmail, tValue, response).execute();
}
public class NetworkResponse implements INetworkResponse {
public void onResponse(String response) {
// here is where you would process the response.
}
public void onError(Exception e) {
}
}
}
Then change the async task constructor to include the new interface.
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
private INetworkResponse myResponse;
public PostDataAsyncTask(String textEmail, String hello, INetworkResponse response) {
data = textEmail;
data1 = hello;
myResponse = response
}
private void postText() {
// do some work
myResponse.onResponse(myResultString);
}
}
You can create a Handler as an Inner class inside your Activity to send data between your thread and UIthread:
public class YourHandler extends Handler {
public YourHandler() {
super();
}
public synchronized void handleMessage(Message msg) {
String data = (String)msg.obj;
//Manage the data
}
}
Pass this object in the header of PostDataAsyncTask
public PostDataAsyncTask(String textEmail, String hello, YourHandler mYourHandler) {
data = textEmail;
data1= hello;
this.mYourHandler = mYourHandler;
}
and send the data in postText() to the Activity:
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
msg = Message.obtain();
msg.obj = responseStr;
mYourHandler.sendMessage(msg);
Log.v("SuccesS", "Response: " + responseStr);
}
I am uploading an image on server by using async task and in the end I want to return value of uploaded file url. How can I do that
I am calling asynctask as
new Config.UploadFileToServer(loginUserInfoId, uploadedFileURL).execute();
and my asynctask function is as:
public static final class UploadFileToServer extends AsyncTask<Void, Integer, String> {
String loginUserInfoId = "";
String filePath = "";
long totalSize = 0;
public UploadFileToServer(String userInfoId, String url){
loginUserInfoId = userInfoId;
filePath = url;
}
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.HOST_NAME + "/AndroidApp/AddMessageFile/"+loginUserInfoId);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
responseString = responseString.replace("\"","");
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Try my code as given below.
public Result CallServer(String params)
{
try
{
MainAynscTask task = new MainAynscTask();
task.execute(params);
Result aResultM = task.get(); //Add this
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
You've almost got it, you should do only one step. As I can see, you are returning the result at the doInBackground method (as a result of calling uploadFile). Now, this value is passed to the onPostExecute method, which is executed on the main thread. In its body you should notify components, which are waiting for result, that result is arrived. There are a lot of methods to do it, but if you don't want to used 3rd party libs, the simplest one should be to inject listener at the AsyncTask constructor and call it at the onPostExecute. For example, you can declare the following interface:
public interface MyListener {
void onDataArrived(String data);
}
And inject an instance implementing it at the AsyncTask constructor:
public UploadFileToServer(String userInfoId, String url, MyListener listener){
loginUserInfoId = userInfoId;
filePath = url;
mListener = listener;
}
Now, you can simply use it at the onPostExecute:
#Override
protected void onPostExecute(String result) {
listener.onDataArrived(result);
super.onPostExecute(result); //actually `onPostExecute` in base class does nothing, so this line can be removed safely
}
If you are looking for a more complex solutions, you can start from reading this article.
I have main activity:
public class ChooseWriteSentenceActivity extends ActionBarActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String userName = "Zdzisiu";
String password = "Ziemniak";
MainServie service = new MainService(this);
boolean isExsist = service.findUser(String userName, String password);
//more code...
}
}
In my app service uses repositories and jsonconsumers but for simpler code I'm skipping them.
public class MyService{
private Context context;
public MyService(Context context){
this.context = context
}
public boolean findUser(String userName, String password){
String resultS = null;
try{
resultS = new QueryExecutorFindUser(context).execute(userName,password).get();
}
catch(Exception ex){
ex.printStackTrace();
}
boolean realRes = jsonConsumer(resultS).getFindUser();
return realRes;
}
}
public class QueryExecutorFindUser extends AsyncTask<String,Void,String> {
protected final String connectionUrl = "http://myWebService:44302/Service.svc/";
protected ProgressDialog progressDialog;
protected Context curContext;
public QueryExecutor(Context context){
curContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(curContext,"Loading...",
"Loading application View, please wait...", false, false);
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
}
protected String doInBackground(String... args){
String result = null;
String url = connectionUrl + args[0] + "/" + args[1];
HttpResponse response = null;
HttpClient httpclient = this.getNewHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
try{
response = httpclient.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
if(response != null){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
result = out.toString();
}
} else{
throw new IOException(statusLine.getReasonPhrase());
}
} catch(Exception ex){
ex.getMessage();
} finally{
if(response != null){
try{
response.getEntity().getContent().close();
} catch(Exception ex){
}
}
}
return result;
}
}
And progress dialog is show but only after all code in onCreatre in ChooseWriteSentenceActivity including doInBacground(...) from QueryExecutor is finished (so it disappears practically at the same time). It looks like sth waiting for thread with QueryExecutorFindUser.doInBackground() and it is runs like synchronously (?), I think that because when I debug code onPreExecute() is running correctly (and start before doInBackground(...)) and progressDialog.isShowing() == true (but not on the screen :( ).
If I remove extends AsyncTask from QueryExecutorFindUser and make private class with this extension in main activity (and run all code from onCreated() including service.findUser() in thisPrivateClass.doInBackground(...)) it works okey.
I prefer to have progressDialog in one place no in all main activities (of cource in practise I use QueryExecutor for all queries not only findUser) but I don't have idea what i am doing wrong. I spent all day on it with no result :(
Dialogs are tied to an Activity and ultimately must be hosted by one. So until your app's activity gets created, the dialog will not display.
I've been having a lot of problems making this code work.
My main activity uses ZXing to scan a barcode, and then I want to take the result of that scan and query my API with it. I know I have to use an AsyncTask to do this, but I've never used one before and I'm having a lot of trouble with it. My goal is to query the API within the AsyncTask, and then update my upcTxt TextView element with the resulting JSON String. What am I supposed to do next in my ReadJSON code?
Here's my main activity code:
public class Barcode extends Activity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt, upcTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
scanBtn = (Button)findViewById(R.id.scan_button);
formatTxt = (TextView)findViewById(R.id.scan_format);
contentTxt = (TextView)findViewById(R.id.scan_content);
upcTxt = (TextView)findViewById(R.id.upc);
scanBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.barcode, menu);
return true;
}
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scan_button){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanResult = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanResult);
new ReadJSON().execute(new String[] {scanResult});
} else {
Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_LONG);
toast.show();
}
}}
And here is my ReadJSON code:
public class ReadJSON extends AsyncTask<String, Void, Void> {
private String content;
private TextView upcTxt;
private String url;
#Override
protected Void doInBackground(String... scanResult) {
url = "REDACTED";
content = "";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
content = Client.execute(httpget, responseHandler);
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Thank you in advance.
Update: Whenever I try to run the code on my phone, I can scan the barcode just fine but then the program crashes once it tries to access the URL.
LogCat:
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:30)
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:1)
01-18 17:26:46.473: D/CrashAnrDetector(376): processName: com.peter.barcodetest
01-18 17:26:46.473: D/CrashAnrDetector(376): broadcastEvent : com.peter.barcodetest data_app_crash
01-18 17:26:46.913: D/PackageBroadcastService(26662): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.peter.barcodetest
01-18 17:26:55.122: I/ActivityManager(376): Process com.peter.barcodetest (pid 24876) (adj 13) has died.
I changed your code to this:
Edited ReadJSON only
AsyncTask (edited)
public class ReadJSON extends AsyncTask<String, Integer, String> {
private String content;
private TextView upcTxt;
private String url;
private static final String TAG = "ReadJSON";
String s = "";
Context context;
ReadJSONCallBack callback;
public ReadJSONTask (Context context, ReadJSONCallBack cb) {
super();
this.callback = cb;
this.context = context;
}
#Override
protected String doInBackground(String... scanResult) {
url = "REDACTED";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
try {
HttpResponse response = Client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
Log.d(TAG, "Got response");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
Log.d(TAG, "Content: " + stringBuilder.toString());
return stringBuilder.toString();
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result) {
callback.setString(s);
}
// method for parsing JSON object
public String parseJSONObject(String output) {
try {
JSONArray jArray = new JSONArray(output);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String id = jObject.getString("id");
String customer = jObject.getString("name");
String description = jObject.getString("description");
Long time = (Long) jObject.get("timeAsDate");
// do something
}
} catch (JSONException e) {
}
return description;
}
}
I'm working on one project and I need to call one AsyncTask, but the onPostExecute method is not called.
This is my class:
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
private String URL;
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
#Override
protected void onPreExecute() {
//notifyListener("A calcular");
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
HttpParams my_httpParams = new BasicHttpParams();
final String proxyHost = android.net.Proxy.getDefaultHost();
final int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1)
{
my_httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient client = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet(url);
Log.d("URL serviço HttpGet", url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
Log.d("RESPOSTA do web service", response);
} catch (Exception e) {
e.printStackTrace();
response = e.getMessage();
Log.e("ERRO de respota", e.getMessage());
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("onPostExecute Serviço", result);
notifyListener(result);
}
}
I have created this method:
public void executeService(String param) {
try {
Log.d("Entrar", "no serviço");
s.execute(new String [] {URL+param});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Erro ao aceder ao web service", e.getMessage());
}
}
to call the task.
these are the results of Log
08-28 17:47:21.936: D/URL serviço HttpGet(2055): http://192.168.56.1:8080/pt.Agile21.Acerola.WebService/rest/acerola?id=g;ana#eu.com
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
As you can see I have all the results of doInBackground(). :S
Someone can help me to understand which is the problem?
Something that I saw now looking for the Log files.. my onPostExeute method returns when I finish my app on purpose.. it is not normal.. :S can someone help me?