I am looking to insert userdata to database by calling URL link to webservice on server:
ex:
this is the link:
http://mydomain.com/AndroidWebService.asmx/nInsertInfo?id=12&lat=23.2222&log=12322
So I want to call this url in hidden mode.
Use android android AsyncTask to post data. It work in android background when application is open.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Like
AsyncTask
AsyncTask
AsyncTask
Thanks.
Thanks all for your valuable solutions.
i have did it by creating WebView
WebView myWebView = (WebView) findViewById(R.id.view1);
myWebView.loadUrl(urll);
then i can manage my WebView as i want: hide it, alignment as error or result returns.
Maybe this example will help you :
public class URLConnectionTask <Result> extends AsyncTask<URL, Void, InputStream> {
#Override
protected InputStream doInBackground(URL... params) {
InputStream is;
HttpUriRequest request;
URI uri;
HttpResponse response;
if (params.length == 0)
return null;
is = null;CredentialsProvider credProvider = new BasicCredentialsProvider();
if (userName != null && userName.length() > 0 && password != null && password.length() > 0)
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(userName, password));
//
DefaultHttpClient http = new DefaultHttpClient();
http.setCredentialsProvider(credProvider);
//
uri = URI.create(params[0].toString());
if (isPost)
request = new HttpPost(uri);
else
request = new HttpGet(uri);
try {
response = http.execute(request);
is = response.getEntity().getContent();
//Log.d(TAG, "doInBackground() response: "+EntityUtils.toString(response.getEntity()));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (processingHandler != null && is != null)
processingResult = processingHandler.processResponse(is);// processingHandler is an instance which implements ProcessingHandler interface (ex. VizMarket). processResponse() is implemented on this class.
return is;
}
#Override
protected void onPostExecute (InputStream result) {
input = result;
if (result == null)
return;
//instruction for inserting data on db ....
try {
result.close();
} catch (IOException e) {
}
}
}
You should call URL in AsyncTask. For instance: Return data from AsyncTask class
U have to use a thread to fetch data from server and insert into to DB or in android you can use AsyncTask.
You can have a search :ClickableSpan
And put your insert code into the OnClick body~
Just like:
String yourTextStr;
SpannableString sp = new SpannableString(yourTextStr);
int start;//the start of your url in the text;
int end ;//the end of your url in the text;
sp.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
//Your Insert Code
}
}, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Related
i want to get the value returns by asynctask after it's been completed. this is my code :
class asyncGet extends AsyncTask<Void, String, String> {
Boolean goterror = false;
#Override
protected String doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response;
try {
request.setHeader("Cache-Control", "no-cache");
request.setHeader("Cache-Control", "no-store");
response = client.execute(request);
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
return str.toString();
} catch (Exception e) {
goterror = true;
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
if (result != null && goterror == false) {
}
}
The async is in another class , I want to show the result when it's done .
How can I return the result from the async ?
thanks
if you want to keep it asynchronous then it is already implemented in your code,
use onPostExecute method, "result" contains the returned data.
Or if you want it to return data synchronously then use the extended asynctask like below:
try {
String result = new asyncGet().execute().get();
} catch (InterruptedException e) {
e.printStackTrace(); //handle it the way you like
} catch (ExecutionException e) {
e.printStackTrace();//handle it the way you like
}
You can create an interface, as follows:
public interface OnStringListener {
void onStringCompleted(String s);
void onStringError(String error);
}
and you will have to create the constructor of your AsyncTask with OnStringListener as parameter:
class asyncGet extends AsyncTask<Void, String, String> {
Boolean goterror = false;
private final OnStringListener mListener;
public asyncGet(OnStringListener listener) {
mListener = listener;
}
//The rest of your code
And in your onPostExecute method you can return the String sending it by the method onStringCompleted:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
if (result != null && goterror == false) {
}
if (mListener != null) {
mListener.onStringCompleted(result);
}
}
Of course, your methods onStringCompleted and onStringError have to be created in the Activity that you want to get the result of your AsyncTask. From there, you will be able to use your result in your other class.
I expect it will be helpful to you!
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
So the philosophy is you override doInBackground and when the doInBackground finishes its task it passes the result to onPostExecute which result is available in your main thread.
Read the Full usage here
and if you still want synchronous execution call get() as explained by #meghraj27
You can implement an interface to an Activity or class where you want the result of the AsynTask and trigger that interface from the AsynTask.
You can refer this post
How to handle return value from AsyncTask
I'm using Android SDK 4.0.3 API15 and I want to run multiple AsyncTasks parallely. I'm getting my data from web server and animating(10 fps) it real-time. But depending on user operations I need to send some data to web server also. When this occurs my animation pauses for a short time (sending data gets into queue and getting data waits it to finish ) and therefore I can't catch the real-time.
This answer is quite explaining but I couldn't make it work. So any help will be very appreciated.
I think I need to use this function to achieve that:
AsyncTask.executeOnExecutor(Executor exec, Params... params)
But I can't pass an executor as a parameter and I can't instantiate an executor. This is my AsyncTask class:
public class GetPlayers extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
rawData="";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
if((rawData = buffer.readLine()) == null){
rawData = "error";
}
} catch (Exception e) {
e.printStackTrace();
}
}
return rawData;
}
#Override
protected void onPostExecute(String result) {
manipulate();
}
}
And I execute it like this:
GetPlayers task = new GetPlayers();
requestString = "web adress is here...";
task.execute(new String[] { requestString });
This is how I do that:
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new MyAsyncTask().execute();
}
where MyAsyncTask is regular AsyncTask subclass. Or you can wrap this all in helper class:
class TaskHelper {
public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task) {
execute(task, (P[]) null);
}
#SuppressLint("NewApi")
public static <P, T extends AsyncTask<P, ?, ?>> void execute(T task, P... params) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
task.execute(params);
}
}
}
and then just do:
TaskHelper.execute( new MyTask() );
or
TaskHelper.execute( new MyTask(), args );
or
TaskHelper.execute( new MyTask(constructorParams), args );
This problem occured to me, when updating my app in AndroidStudio to
sdk 25 from Intelliy using Android 2.3
Just the little change (executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, string1, ...); ) works perfectly.
I have an AsyncTask running in a Service for download and
create AsyncTasks for upload in no service.
I'm trying to see how works an Asynctask class in android. In particular i want reveal in real time the status of the class for see when it is running and when it has finished. For do this, i have created a class that extend the main activity and another class that is the asynctaks class.
This is my main class:
public class PhotoManagement extends Activity{
private String numberOfSelectedPhotos;
private Bitmap currentImage;
private String initConfiguration = "http://www.something.com";
private String response;
private ArrayList<String> formatPhotoList = new ArrayList<String>(); //create a list that will contains the available format of the photos downloaded from the server
private ArrayList<String> pricePhotoList = new ArrayList<String>(); //create a list that will contains the available price for each format of the photos
DownloadWebPageTask webPage = new DownloadWebPageTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
if(webPage.getStatus() == AsyncTask.Status.PENDING){
Log.i("STATUS","PENDING");
}
if(webPage.getStatus() == AsyncTask.Status.RUNNING){
Log.i("","RUNNING");
}
if(webPage.getStatus() == AsyncTask.Status.FINISHED){
Log.i("","FINISHED");
}
}
}
As you can see i want only see the passages of the status with a simple log.
And here there is the asynctask class.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient(); //create a new http client
HttpGet httpGet = new HttpGet(url); //create a new http request passing a valid url
try {
HttpResponse execute = client.execute(httpGet); //try to execute the http get request
InputStream content = execute.getEntity().getContent(); //prepare the input stream to read the bytes of the request
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s; //until is present a line to read, the response variable store the value of the lines
}
} catch (Exception e) {
Log.i("MyApp", "Download Exception : " + e.toString()); //Print the error if something goes wrong
}
}
return response; //return the response
}
#Override
protected void onPostExecute(String result) {
result = doInBackground(initConfiguration); //take the result from the DownloadWebPageTask class
result = result.replace("null", "");
Log.i("RESULT",""+result);
//find the price and format value from the result using XmlPullParser
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( result ) );
int attributeNumber = xpp.getAttributeCount();
int eventType = xpp.getEventType();
String currentTag = null;
while(eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
if (currentTag.equals("product")){
xpp.getAttributeValue(null, "name");
formatPhotoList.add(xpp.getAttributeValue(null, "name"));
Log.i("FORMAT PHOTO",""+xpp.getAttributeValue(null, "name"));
}
}
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.i("","ERROR XML PULL PARSER");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("","ERROR IOEXCEPTION");
}
}
}
}
As you can see i have implemented also the method onPostExecute that should be called when the asynctask method has finished to execute the instructions right?
So at this point i don't understand why my log RUNNING and my log FINISHED never appear on the log cat.
What i'm doing wrong?
I'm tried to follow this topic Android, AsyncTask, check status? but in my case it isn't working.
Thanks
Problem :
You are creating object like
DownloadWebPageTask webPage = new DownloadWebPageTask();
But you are calling asynctask on different object,
new DownloadWebPageTask().execute(initConfiguration);
Solution :
It should be like
webPage.execute(initConfiguration);
#Override
protected void onResume(){
super.onResume();
new DownloadWebPageTask().execute(initConfiguration);
here do like this
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
You didn't implement webPage.execute(), add it
Most probably the task hasn't finished or even started yet. As you probably know the AsyncTask is doing it's (background) work on a different thread, so your onResume is running in parallel with it. You can either use the task's get() method to wait for it to finish and get the result of the doInBackground() method and then query for it's status or notify your activity from the task's onPostExecute() method to let it know (and log) that it has finished. I don't recommend you the first option because it will actually block the UI thread and will make your usage of AsyncTask pointless.
i wrote those threads:
How to manage multiple Async Tasks efficiently in Android
Running multiple AsyncTasks at the same time -- not possible?
but didnt find answer for my question, maybe someone can help..
I have android app which makes Login POST and getting json response,
if the Json is OK i need to POST another data to get another response.
i have extends Async Class which doing the post to the URL:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
private HashMap<String, String> mData = null;
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
return null;
}
return str;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray Loginjson = new JSONArray(result);
strStt = Loginjson.getJSONObject(0).getJSONObject("fields").getString("status");
if (strStt.equals("ERR")) {
ErrorMsg("Authentication failed");
} else if (strStt.equals("OK")) {
ErrorMsg("Login OK!!!");
ClientPage();
} else {
ErrorMsg("Connection Error");
}
} catch (JSONException e) {
ErrorMsg("Connection Error");
}
}
}
Now - i need to get another POST if the status is Error. do i need to make another Async class? with the same all procedures ? the issue is only the onPostExecute part is different.. actually the "doInBackground" will be always the same..
any idea how can i easily do multiple posts in the same activity?
Firstly, since your doInBackground() code will always stay the same, I recommend you move it into a general utility class.
Beyond that, you can go one of two ways:
Create a new AsyncTask for each type of request that can call your utility class, and have its own onPostExecute()
Create one AsyncTask that has a flag in it, which can be checked in the onPostExecute() method to see what code needs to be executed there. You will have to pass the flag in in the constructor or as a parameter in execute.
You can use a parameter at AsyncHttpPost constructor/execute or global variable to indicate if it is first or second POST (by other words - a flag). Then just create and execute another instance of AsyncHttpPost in onPostExecute (only if parameter/variable is set as "first POST").
Here is my issue:
I have a list of values which I retrieve from server.
These values fill ListView in the UI.
I cannot continue loading the View and showing it to user until the list is full.
Since Android forces me to make http calls in separate thread, my question is how do I create 1 class that does the httprequests and in the calling class I wait until I get response from the HttpRequest and only then I proceed loading the View?
Right now I have this class that does the requests:
public class WapConnector extends AsyncTask<String, String, String>{
private static final String TAG = "WapConnector";
private String html = "";
private Handler mHandler;
private String server = "http://....whatever";
private String callUrl = "/api/";
private String params = "login?u=Admin&pw=234234&format=json";
private int _callstate = 1;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
String fullUrl = "";
Log.i(TAG,fullUrl);
if(params.length() > 0){
fullUrl = server + callUrl + params + "&alf_ticket=" + Globals.getInstance().getTicket() + "&udid=" + Globals.getInstance().udid() + "&phoneNumber=" + Globals.getInstance().phoneNumber();
}
else{
fullUrl = server + callUrl + "?udid=" + Globals.getInstance().udid() + "&alf_ticket=" + Globals.getInstance().getTicket() + "&phoneNumber=" + Globals.getInstance().phoneNumber();
}
Log.i(TAG,fullUrl);
response = httpclient.execute(new HttpGet(fullUrl));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Log.i(TAG,responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(TAG + "onPostExecute",result);
activity.getClass().handleResponse();
//main load
JSONObject jobj;
JSONObject jvalue;
try {
jobj = new JSONObject(result);
if(_callstate == 1){
jvalue = jobj.getJSONObject("data");
String ticket = jvalue.getString("ticket");
Log.i("loginwap",ticket);
Globals.getInstance().setTicket(ticket);
_callstate = 2;
}
else{
jvalue = jobj.getJSONObject("countries");
JSONArray countries = jvalue.getJSONArray("countries");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is how I make calls from Parent classes:
WapConnector wap = new WapConnector();
wap.setCallUrl("/anyurl/");
wap.callstate(3);
wap.setParams("");
wap.execute("");
Now my issue is that since the request runs in thread, once I call wap.execute(), my Activity continues to load, but I want it to wait until I get response, parse the response and only then continue to load.
thanks everyone for replies.!!!
Pass in a context to your class from the activity you are calling it from. Overload the onPreExecute() to show a ProgressDialog and then overload onPostExecute() to hide the ProgressDialog. This gives you blocking while letting the user you are loading.
There is a kinda hacky way to get more control. If you want to keep the AsyncTask as a separate class but allow it to update UI elements in another Activity, define a Handler in that Activity and then pass it in the constructor of the the AsyncTask. You can then send a message in the onPostExecute() method of your AsyncTask to the handler to tell it to update the UI. You will need to make sure the handler is properly handling the message your AsyncTask is sending back. Could be a little cleaner, but it works and will allow you to reuse an asyncTask that makes a network call across activities.