I have a AsyncTask<Task, Void, Boolean> thread in my Android application. And I want to show message through Toast.makeText() when this thread completes its execution. For this I have added Toask.makeText() inside if as well as inside else of doInBackground method. The thread is completing its execution succesfully but the toast's message does not appears. So what can be the problem?
Code:
#Override
protected Boolean doInBackground(Task... arg0) {
try {
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode()<205)
{
/*this is the message inside if*/
Toast.makeText(context, "inside -IF", Toast.LENGTH_SHORT).show();
return true;
}
else
{
/*this is the message inside else*/
Toast.makeText(context, "inside -ELSE", Toast.LENGTH_SHORT).show();
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Toast work in Main thread you are trying to show Toast in Background Thread (doInBackground). Move your toast code to onPostExecution callaback and you will be able to see Toasts.
The Task it is doing is in background, it won't show toast as it is in background.
Background tasks don't affect your UI or main thread.
The thread is completing its execution succesfully but the toast's
message does not appears
Because doInBackground method run on non-ui-Thread. and application only show Alert,Toast and update UI elements from UI-Thread only.
To show Toast from doInBackground wrap Toast related code inside runOnUiThread method
OR
return response from doInBackground method and use onPostExecute method to show Toast.
As mentioned by other people, you shouldn't have any UI related changes/activities on the background thread. Do it on the main thread which onPostExecute method does. Here's an example
private class DoSomethingTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//Do background process here. Make sure there are no UI related changes here
return null;
}
protected void onPostExecute(Void x)
{
//Do UI related changes here
}
}
Using your code:
private class DoSomethingTask extends AsyncTask<Void, Void, Void> {
int statusCode;
#Override
protected Void doInBackground(Task... arg0) {
try {
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
protected void onPostExecute(Void x)
{
//Do UI related changes here
if(statusCode < 205)
{
/*this is the message inside if*/
Toast.makeText(context, "inside -IF", Toast.LENGTH_SHORT).show();
return true;
}
else
{
/*this is the message inside else*/
Toast.makeText(context, "inside -ELSE", Toast.LENGTH_SHORT).show();
return false;
}
}
}
Hope this helps!
Related
In the next code I can not make the toast message inside the doInBackground method jump.
When I delete this line, the writing of the "error" string into the edittext performed fine.
What am I doing wrong?
private class Verify extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
username = etusername.getText().toString();
password = etpass.getText().toString();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
postParameters.add(new BasicNameValuePair("password", password));
String response = null;
String result;
try {
response = CustumHttpClient.executeHttpPost(url_verify_detials, postParameters);
result = response.toString();
result = result.replaceAll("\\s+", "");
if (!result.equals("0")) {
Intent in = new Intent(MainActivity.this, danpage.class);
startActivity(in);
} else {
Toast.makeText(getApplicationContext(), "this is my Toast message!!", Toast.LENGTH_LONG)
.show();
etusername.setText("Error");
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
You can't place any code which does anything to the user interface inside the doInBackground method. If you want to show your toast you will need to return a result to onPostExecute and deal with it there.
How do you return a result to onPostExecute? In your class definition the third parameter inside the <> is the type that you will want to return in the onPostExecute method so you declaration will look like
private class Verify extends AsyncTask<Void, Void, String>
and you onPostExecute will look like
protected void onPostExecute(String result) {
Please see the reference for a good example. http://developer.android.com/reference/android/os/AsyncTask.html
You can use publishProgress and onProgressUpdate to make a Toast:
private static final int ERROR = -1;
...
try {
response = CustumHttpClient.executeHttpPost(url_verify_detials, postParameters);
result = response.toString();
result = result.replaceAll("\\s+", "");
if (!result.equals("0")) {
Intent in = new Intent(MainActivity.this, danpage.class);
startActivity(in);
} else {
//Toast.makeText(getApplicationContext(), "this is my Toast message!!", Toast.LENGTH_LONG)
// .show();
//etusername.setText("Error");
publishProgress(ERROR);
}
} catch (Exception e) {
}
...
#Override protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (values[0]==ERROR){
Toast.makeText(MainActivity.this, "this is my Toast message!!", Toast.LENGTH_LONG)
.show();
etusername.setText("Error");
}
}
You must use runOnUIThread method to execute this code.
You must execute ui methods in that thread.
Yeap ... toast has to be displayed on the UI thread. When you don't return a result from doInBackground you can return a Boolean instead and use it in onPostExecute to show your Toast. onPostExecute is executed on the UI thread. runOnUIThread is also a solution ...
I am creating an android app that depends on data that the app gets from the database. To get this data I have the following class (this class gets data from the database in JSON, translates it and returns it):
public class Json {
public String jsonResult;
private Activity activity;
private String url = "http://json.example.org/json.php";
private String db, query;
public Json(Activity activity) {
this.activity = activity;
}
public String accessWebService(String db, String query) {
JsonReadTask task = new JsonReadTask();
this.db = db;
this.query = query;
task.execute(new String[] { url });
try {
task.get();
} catch (InterruptedException e) {
Toast.makeText(activity.getApplicationContext(), "FATAL ERROR: The thread got interrupted",
Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
Toast.makeText(activity.getApplicationContext(), "FATAL ERROR: The thread wasn't able to execute",
Toast.LENGTH_LONG).show();
}
return jsonResult;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(activity);
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
// add post data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("db", db));
nameValuePairs.add(new BasicNameValuePair("query", query));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
if (jsonResult.isEmpty()) {
Toast.makeText(activity.getApplicationContext(),
"Error, connection is up but didn't receive data. That's strange...", Toast.LENGTH_LONG)
.show();
this.cancel(true);
}
} catch (ClientProtocolException e) {
// Toast.makeText(activity.getApplicationContext(),
// "Error, Client Protocol Exception in JSON task",
// Toast.LENGTH_LONG).show();
Log.i("Json", "Error, Client Protocol Exception in JSON task");
this.cancel(true);
} catch (IOException e) {
// Toast.makeText(activity.getApplicationContext(),
// "Error, Please check your internet connection",
// Toast.LENGTH_LONG).show();
Log.i("Json", "Error, Please check your internet connection");
this.cancel(true);
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
Toast.makeText(activity.getApplicationContext(), "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
}// end async task
}
I noticed that my app freezes while accessing the database. After some googling, I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a progressDialog like so (I also deleted the .get() method):
private final ProgressDialog dialog = new ProgressDialog(activity);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
protected void onPostExecute(String result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
but the dialog didn't show up and I got NullPointerException because the app only works when there is data:
result = json.accessWebService(db, query);
(maybe an important thing to mention: I also use this method in for loops)
So now my question is: How can I change my app so that I get a ProgressDialog while accessing the database and without getting NullPointerException? I fear that I have to rearchitect my whole app and if I have to do this, how do I do this? I hope you guys understand my question and have a fix for this because I really need help. Thanks in advance.
P.S. Sorry if my English is not that good, I'm not a native speaker.
... I found out it was the .get() method in the accessWebService() method caused this. I tried to implement a progressDialog...
That is right. get() is a blocking call and simply adding a ProgressDialog won't fix it. You need to remove .get() and that will probably fix the issue of your ProgressDialog not showing.
An AsyncTask must be executed on the main Thread so make sure you are doing that.
Another problem you have is Toast.LENGTH_LONG).show(); runs on the UI and you have it in doInBackground() which cannot happen. You need to send the result to onPostExecute() and you can display your Toast there if need. This could also be done in onProgressUpdate().
This null pointer exception happens because of result value was null. put the condition before
if(result != null ) {
// CODE FOR PARSING
} else {
return;
}
You can start showing progress bar before asyncTask is started and finish showing when asyncTask is finished.
Pass handler to asyncTask and sendMessage onPostExecute method. Then handle message on UI thread and hide progress bar
For example there is handler field in UI (mainActivity). There you should handle hiding progress bar:
public Handler refreshChannelsHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case EPGManager.ERROR_MESSAGE:
//do some stuff
break;
case EPGManager.SUCCESS_MESSAGE:
//do some stuff
break;
}
super.handleMessage(msg);
}
};
Then you can call asyncTask with your handler
epgManager.loadChannels(refreshChannelsHandler);
AsyncTask is inside the method so it looks like this:
public void loadChannels(Handler handler) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
try {
//do AsyncTask Job
} catch (Exception e) {
return new LoadingResult((Handler) params[0], false);
}
return new LoadingResult((Handler) params[0], false);
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
LoadingResult loadingResult = ((LoadingResult)o);
sendMessageToHandler(loadingResult.handler, loadingResult.isSuccess);
}
};
task.execute(handler);
}
Here is method:
private void sendMessageToHandler(Handler handler, boolean isSuccess) {
handler.sendEmptyMessage(isSuccess ? SUCCESS_MESSAGE : ERROR_MESSAGE);
}
And finally inner class
private class LoadingResult {
private Handler handler;
private boolean isSuccess;
public LoadingResult(Handler handler, boolean isSuccess) {
this.handler = handler;
this.isSuccess = isSuccess;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
Ow, and don't forget constants
public static final int SUCCESS_MESSAGE = 1;
public static final int ERROR_MESSAGE = -1;
Hope it helps :)
Friends ,i need help to android httppost data to server using Asynctask or Threads
I need to send data to my server when i click post button.But when i click it app need to go to next page and data need to send through as background process.I'm new to Android.I don't know what is exactly use for this kind of task (Threads or Asyanctask).
I tried this code but it will give me exception error
public void startProgress(final String name) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
send(name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
public void send(String name)
{
// get the message from the message text box
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8080/Test");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String co2 =input_field.getText().toString();
nameValuePairs.add(new BasicNameValuePair("Name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Toast toast = Toast.makeText(getApplicationContext(), "Got it ", Toast.LENGTH_SHORT);
toast.show();
httpclient.execute(httppost);
input_field.setText("");
} catch(Exception e){
Toast toast2 = Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT);
toast2.show();
}
}
but if i use it this way it works.(text is TextView item in that page)
public void startProgress(final String name) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.post(new Runnable() {
#Override
public void run() {
send(name);
}
});
}
};
new Thread(runnable).start();
}
What happen in bellow piece of code can you please explain about this also
text.post(new Runnable() {
#Override
public void run() {
send(name);
}
});
please help me to solve this problem.If there is better way to do my need please mentioned it .Because it have very less experience about Android development
You can do this by using AsyncTask like this:
public class HttpPostExanple extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
BufferedReader inBuffer = null;
String url = "http://10.0.2.2:8080/Test";
String result = "fail";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name", params[0]));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(formEntity);
httpClient.execute(request);
result="got it";
} catch(Exception e) {
// Do something about exceptions
result = e.getMessage();
} finally {
if (inBuffer != null) {
try {
inBuffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
protected void onPostExecute(String page)
{
//textView.setText(page);
Toast toast = Toast.makeText(getApplicationContext(), page, Toast.LENGTH_SHORT);
toast.show();
}
}
And you need to have this in your main method
new HttpPostExample().execute(new String[] {name});
Check this out.
Hope this will help you.
You should implement something like this:
new Thread(new Runnable() {
public void run() {
send(name); // if this method need to access the UI interface you have to use .post method
}
}).start();
About your question: the .post method causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread. [reference]
And this is required because without this method you violate the single thread model: the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. In your piece of code, the TextView is manipulated on a worker thread, which can cause really weird problems.
As you can see, If the method inside your thread need to access the UI you should use .post method, and this make more laborious the code. So the right solution may be use the AsyncTask that will manage for you the complexity of the threads. You have to put the piace of code that need to access on the UI, in the onPostExecute() method
I suggest you to use robospice or other frameworks as alternative:
Volley
DataDroid
REST Provider
REST Droid
PostMan (rings twice) Lib
Ion
droidQuery
Android Job Queue
Goro
because activity can be recreated before onPostExecute reached. AsyncTask is not good example for networking in Activity.
I am getting the exception android.os.NetworkOnMainThreadException when I tried to use the following codes:
public class CheckServer extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Runnable runn = null;
HttpTask.execute(runn);
}
private class HttpTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection urlConnection = null;
URL theURL = null;
try {
theURL = new URL("http://192.168.2.8/parkme/Client/clientquery.php?ticket=66t");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
urlConnection = (HttpURLConnection) theURL.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String response = null;
try {
response = readInputStream(urlConnection.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
private String readInputStream(InputStream is) {
// TODO Auto-generated method stub
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return total.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}}
If possible can someone tell me how to use it inside an Async Task and get the output? I tried but can't seem to get anywhere.
NetworkOnMainThread Exception occurs because you are running a network related operation on the main UI Thread.This is only thrown for applications targeting the Honeycomb SDK or higher
You should be using asynctask.
http://developer.android.com/reference/android/os/AsyncTask.html
In onCreate()
new TheTask().execute();
You can also pass parameters like url to the constructor of AsyncTask and use the same in doInBackground()
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)//return result here
{
//http request. do not update ui here
return null;
}
protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui using the result returned form doInbackground()
}
}
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
Ok, lets do it step by step ...
1) create private class extending AsyncTask
private class HttpUrlConnectionTask extends AsyncTask {
2) Override the doInBackground() method, this will do the heavy load
#Override
protected Object doInBackground(Object... params) {
// your HttpUrlConnection code goes here
return response;
3) Once the job is done and returns, the onPostExecute() method will be called. The result parameter contains the return value of doInBackground() - so response.
#Override
protected void onPostExecute(Object result) {
Within this method you can update your UI.
4) Finally lets have a look onto the HttpUrlConnection code
HttpURLConnection urlConnection = null;
URL theURL = new URL(url);
urlConnection = (HttpURLConnection) theURL.openConnection();
String response = readInputStream(urlConnection.getInputStream());
return response;
Hope this helps. Happy coding!
#Raghunandan comes with a really good explanation of how AsyncTask works
Here you go:
public static class InitializeTask extends MyAsyncTask<String, String, String> {
private Activity activity;
private ProgressDialog dialog;
public InitializeTask(Activity activity) {
this.activity = activity;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://192.168.2.8/localhost/parkme/Client/clientquery.php?ticket=");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
return convertStreamToString(inputstream);
} else {
return "Unable to complete your request";
}
} catch (ClientProtocolException e) {
return "Caught ClientProtocolException";
} catch (IOException e) {
return "Caught IOException";
}
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
return "Stream Exception";
}
return total.toString();
}
}
A little side note, it is generally considered bad code to catch just Exception, since this will catch anything, and you are not accounting for what it is.
To use the AsyncTask in the Activity do this:
InitializeTask task = new InitializeTask(this)
task.execute()
Exactly as it says, network activity isn't allowed on the thread the activity ran in. Moving your code to an Asynctask is the way to do it properly. Though if you're just trying to get your concept working still you can do this...
//lazy workaround with newer than gingerbread
//normally UI thread can't get Internet.
if(Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And then the UI thread actually can. I wouldn't release anything like this however, I haven't even tried infact. It's just my lazy debugging move I use a lot.
I have an Activity (RecipiesActivity) that is opened by clicking on the "Next" button of the Main Activitiy of my application.
In the RecipiesActivity onCreate, I want to call a webservice in an AsyncTask. For now, since I have not implemented the webservice yet, I am just calling a webservice provided by bitly (but this is irrelevant to my problem).
The problem is that although the webservice gets called and no exception is thrown, a result is return from the doInBackground, but my onPostExecute is not called. I have done some research and I have found the possible reasons as listed below - but none seem to be my case:
onPostExecute parameters do not match the AsyncTask parameters - in my case they match
A bug in android that does not allow the AsyncTask to be executed in the UI thread. It is supposadely overcomes by using Class.forName("android.os.AsyncTask") - I tried this and did not make any difference
AsyncTask is not started from the UI thread - in my case I believe it is
doInBackground does not return - in my case it does, I have stepped through it with the debugger
#Override is not used before onPostExecute - in my case I am using #Override
The code is below:
public class RecipiesActivity extends Activity {
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipies);
tv = (TextView) findViewById(R.id.Response);
//Start the WS call in an AsyncTask
new CallWS().doInBackground("https://api-ssl.bitly.com/v3/shorten?login=maskedLogin&apiKey=maskedKey&longUrl=http%3A%2F%2Fgoogle.com%2F");
}
private class CallWS extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet get_request = new HttpGet(params[0]);
try
{
HttpResponse httpResponse = httpClient.execute(get_request, localContext);
//int responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream istream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(istream));
try
{
result = br.readLine();
}
catch (Exception e)
{
//TODO Handle the IOException that the readline may throw
}
finally
{
istream.close();
}
}
}catch (Exception e)
{
//TODO Handle the IOException and the ClientProtocolException that the
// httpClient.execute can throw
}
finally
{
httpClient.getConnectionManager().shutdown();
}
return result;
}
#Override
protected void onPostExecute(String result)
{
if (result == null)
{
tv.setText("The result is NULL");
}
else
{
tv.setText(result);
}
}
}
}
Your help is appreceiated,
thanks
Instead of doInBackground(), simply call the execute() method of the AsyncTask. Calling doInBackground() does what it says on the tin: calls doInBackground() (in the same thread) and returns. It won't call onPostExecute() for you. execute() will start a background thread, call doInBackground() on the background thread, then post the result of doInBackground() to onPostExecute() on the UI thread.
Try changing this line
new CallWS().doInBackground("https://api-ssl.bitly.com/v3/shorten?login=maskedLogin&apiKey=maskedKey&longUrl=http%3A%2F%2Fgoogle.com%2F");
to
new CallWS().execute("https://api-ssl.bitly.com/v3/shorten?login=maskedLogin&apiKey=maskedKey&longUrl=http%3A%2F%2Fgoogle.com%2F");
Make sure your onPostExecute function has #Override