Goodmorning,
I have a button on my android app that launches a search on the web (through google endpoints) through an AsyncTask. My problem is that the button does not "unclick" until the AsyncTask is completed, which may take several seconds. When the internet connection is slow, this even makes the application crash, in any case the application is completely stuck until the AsyncTask is completed. Now the reason for using AsyncTask was exactly to eliminate this problem, so I don't really get what happens!
Here is the OnClickListener:
SearchListener = new OnClickListener() {
#Override
public void onClick(View v) {
String cname=TextCourse.getText().toString();
if (!cname.isEmpty()){
try {
CollectionResponseWine listavini= new QueryWinesTask(messageEndpoint,cname,5).execute().get();
} catch (InterruptedException e) {
showDialog("Errore ricerca");
e.printStackTrace();
} catch (ExecutionException e) {
showDialog("Errore ricerca");
e.printStackTrace();
}
} else{
showDialog("Inserisci un piatto");
}
}
};
and here is the AsyncTask that is being called:
private class QueryWinesTask
extends AsyncTask<Void, Void, CollectionResponseWine> {
Exception exceptionThrown = null;
MessageEndpoint messageEndpoint;
String cname;
Integer limit;
public QueryWinesTask(MessageEndpoint messageEndpoint, String cname, Integer limit) {
this.messageEndpoint = messageEndpoint;
this.cname=cname;
this.limit=limit;
}
#Override
protected CollectionResponseWine doInBackground(Void... params) {
try {
CollectionResponseWine wines = messageEndpoint.listwines().setCoursename(cname).setLimit(limit).execute();
return wines;
} catch (IOException e) {
exceptionThrown = e;
return null;
//Handle exception in PostExecute
}
}
protected void onPostExecute(CollectionResponseWine wines) {
// Check if exception was thrown
if (exceptionThrown != null) {
Log.e(RegisterActivity.class.getName(),
"Exception when listing Messages", exceptionThrown);
showDialog("Non ci sono vini associati al tuo piatto. Aggiungine uno!");
}
else {
messageView.setText("Vini piu' votati per " +
cname + ":\n\n");
for(Wine wine : wines.getItems()) {
messageView.append(wine.getName() + " (" + wine.getScore() + ")\n");
}
}
}
}
...execute().get() is blocking. It makes UI thread wait for Task to complete.
Don't do get(). Use onPostExecute() to get the result (wines) of task and update the UI.
Related
In my Android async task class, I'm fetching data from an Azure server to local database inside DoinBackground method
But before finishing the DoinBackground method, it's executing the OnPostExecute method
Inside OnPostExecute method I am disabling the ProgressBar
Help me to solve this issue.
My code:
public class AsyncTaskSync_UserGroupMappingTableClass extends AsyncTask<String, String, Boolean>
{
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... values)
{
try
{
mToDoTable_Form5_SPINNER_DataTable456_ServerAzure
.execute(new TableQueryCallback<FormsObjectTable2TaskHopsSPinnerValues>() {
public void onCompleted(List<FormsObjectTable2TaskHopsSPinnerValues> result, int count, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
if (!result.equals("")) {
for (int i = 0; i < result.size(); i++) {
/*Table 5 SPinner Data Table*/
IdValue_TableValue5 = result.get(i).getId();
ImeiStringval1_TableValue5 = result.get(i).getImeINumberValOne();
Spinner_IDStringVal1_TableValue5 = result.get(i).getSpinner_id_StringOne();
Spinner_data_StringVal1_TableValue5 = result.get(i).getSPinner_data_Value_StringOne();
Log.i("From SErver DataBase", " Spinner : " + ImeiStringval1_TableValue5 + " : " + Spinner_IDStringVal1_TableValue5 + " : " + Spinner_data_StringVal1_TableValue5);
Asynxfor_DATAinsert5_SpinnerTable(IdValue_TableValue5, ImeiStringval1_TableValue5, Spinner_IDStringVal1_TableValue5, Spinner_data_StringVal1_TableValue5);
}
} else {
Log.i("Data Retrieval Not Found", "No Data In Server For Specific IMEI......!");
}
} else {
Log.i("SOme Exception", "Data Retrieval From Server FORMTABLE1 Data......!");
exception.printStackTrace();
}
}
});
}
catch (Exception e)
{
e.printStackTrace();;
Log.i("Data Retrieval", "Exception Occur......!");
}
// PrgDialog.dismiss();
return null;
}
#Override
protected void onPostExecute(Boolean results)
{
try
{
Log.i("DONE ", "Data Sync Done Successfully 5 Spinner Values");
PrgDialog.dismiss();
}
catch (Exception e)
{
e.printStackTrace();
Log.i("Exception ", "Post Excecute");
}
}
};
Edit 1
My Logcat message:
// From OnPostExecute first Executing also disabling the Progressbar
DONE: Data Sync Done Successfully Form Master 1
// From Doinbackground
From Server database
The requests you are doing inside doInBackground are made asynchronusly that's means that doInBackground is already execute before you get the TableQueryCallback. In other words It's a thread which is launching another thread. I think you do not need to surround it in an AsyncTask, you could handle your respond on TableQueryCallback.onCompleted() with a Handler or an Interface.
I am able to retrieve the access token of google account.But I am unable to get the userprofile info.I am getting null pointer exception.Why i cant understand.
Below I have provided two methods using which we get access token and also gets the userprofile info.
It would be great if you help me.
MainActivity.java
private void tryAuthenticate() {
if (isFinishing()) {
return;
}
mToken = null;
setProgressBarIndeterminateVisibility(true);
AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
try {
mToken =
GoogleAuthUtil.getToken(MainActivity.this, mChosenAccountName, "oauth2:"
+ Scopes.PLUS_LOGIN + " " + "https://www.googleapis.com/auth/plus.login" + " "+" https://www.googleapis.com/auth/plus.profile.agerange.read"+" " +YouTubeScopes.YOUTUBE + " "
+ YouTubeScopes.YOUTUBE_UPLOAD);
} catch (GooglePlayServicesAvailabilityException playEx) {
GooglePlayServicesUtil.getErrorDialog(playEx.getConnectionStatusCode(),
MainActivity.this, REQUEST_GMS_ERROR_DIALOG).show();
} catch (UserRecoverableAuthException userAuthEx) {
// Start the user recoverable action using the intent
// returned by
// getIntent()
startActivityForResult(userAuthEx.getIntent(), REQUEST_AUTHENTICATE);
return false;
} catch (IOException transientEx) {
// TODO: backoff
Log.e(this.getClass().getSimpleName(), transientEx.getMessage());
} catch (GoogleAuthException authEx) {
Log.e(this.getClass().getSimpleName(), authEx.getMessage());
}
return true;
}
#Override
protected void onPostExecute(Boolean hideProgressBar) {
invalidateOptionsMenu();
if (hideProgressBar) {
setProgressBarIndeterminateVisibility(false);
}
if (mToken != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
saveAccount();
}
});
}
loadData();
}
};
task.execute((Void) null);
}
private void loadProfile() {
new AsyncTask<Void, Void, Person>() {
#Override
protected Person doInBackground(Void... voids) {
GoogleCredential credential = new GoogleCredential();
credential.setAccessToken(mToken);
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
Plus plus =
new Plus.Builder(httpTransport, jsonFactory, credential).setApplicationName(
Constants.APP_NAME).build();
try {
return plus.people().get("me").execute(); //here am getting null pointer exception
} catch (final GoogleJsonResponseException e) {
if (401 == e.getDetails().getCode()) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
GoogleAuthUtil.invalidateToken(MainActivity.this, mToken);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
tryAuthenticate();
}
}, mCurrentBackoff * 1000);
mCurrentBackoff *= 2;
if (mCurrentBackoff == 0) {
mCurrentBackoff = 1;
}
}
} catch (final IOException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Person me) {
mUploadsListFragment.setProfileInfo(me);
}
}.execute((Void) null);
}
It seems as if you have mixed and matched a lot of things all together. The line at which you are getting a Null Pointer is because the me is not defined anywhere else in the program and hence when the get method is called it is not able to find the value.
Secondly, you can separate out the code in two different files if you want to perform a set of two different operations. If you just want to retrieve the information regarding the profile information of a Google+ User account please follow the tutorial.
My MainActivity has 2 views: TextView and a Button. On button click, I am running an AsyncTask which further creates 10 new AsyncTasks for network operations. Every new task creation is delayed by 1 sec. The code is:
public class MainActivity extends ActionBarActivity
{
TextView tv;
Button t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
t = (Button) findViewById(R.id.toggleButton1);
t.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
getData();
}
});
}
void getData()
{
SuperNetworkAsyncTask s = new SuperNetworkAsyncTask();
s.execute("");
}
private class SuperNetworkAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
for(int i=0;i<10;i++)
{
{
nTask = new NetworkAsyncTask();
nTask.execute("");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return "";
}
#Override
protected void onPostExecute(String result)
{
}
}
private class NetworkAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
return String.valueOf(System.currentTimeMillis());
}
#Override
protected void onPostExecute(String result)
{
tv.setText(result);
}
}
}
I was expecting that the moment first NetworkAsyncTask execute method is called, it will start execution. But when I run it, I do not find any NetworkAsyncTask begin its execution until the control comes out of SuperNetworkAsyncTask. Is there any way to push the execution of NetworkAsyncTask thread as soon as execute method is called?
Some clarifications:
Why NetworkAsyncTask are created by SuperNetworkAsyncTask? Because If I create the NetworkAsyncTask in main thread, I get my UI freeze for some time.
Why making 10 object? The purpose of NetworkAsyncTask is to read data from a server at interval of 1 sec for n seconds, here n=10.
Part 2: Updates after doing some tests.
Observation 1:
As a fellow Brian shared a way to avoid creating AsyncTasks in nested way, I tried his code:
void getData() {
Runnable runnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
nTask = new NetworkAsyncTask();
nTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
}
This freezes my UI for few seconds and then the screen is updated in a fraction of second. It is quite surprising to me too.
Observation 2:
With java.lang.Thread, I experimented to make sure that 1) The threads should be executed right away when run() called. 2) The next task will be created only after previous task is finished.
Code:
public static void main(String[] args) {
myThread m;
for (int i=0;i<10;i++)
{
m=new myThread(String.valueOf(i));
m.start();
synchronized (m)
{
try {
m.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class myThread extends Thread
{
public String name = "";
public myThread(String n)
{
name = n;
}
public void run()
{
synchronized (this)
{
System.out.println(" Thread Name = " + name);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyAll();
}
}
}
Output:
Thread Name = 0
Thread Name = 1
Thread Name = 2
Thread Name = 3
Thread Name = 4
Thread Name = 5
Thread Name = 6
Thread Name = 7
Thread Name = 8
Thread Name = 9
Based in this, I updated my NetworkAsyncTask & SuperNetworkAsyncTask as:
private class NetworkAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
synchronized (this)
{
return String.valueOf(System.currentTimeMillis());
}
}
#Override
protected void onPostExecute(String result)
{
synchronized (this)
{
tv.setText(result);
notifyAll();
}
}
}
private class SuperNetworkAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
for(int i=0;i<10;i++)
{
nTask = new NetworkAsyncTask();
nTask.execute(url);
synchronized (nTask)
{
try {
nTask.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return "";
}
#Override
protected void onPostExecute(String result)
{
}
}
With this code the wait() keeps on waiting indefinitely.
Finally I replaced:
nTask.execute(url);
with
nTask.executeOnExecutor(THREAD_POOL_EXECUTOR, "");
This worked well as expected.
The UI will be updated only at onPostExecute(). See notes on AsyncTask
Click here! And Try to avoid 10 AysncTasks, it does not make any sense.
You don't need to use a "super async task" use a runnable and then create new async tasks in parallel
void getData() {
Runnable runnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
nTask = new NetworkAsyncTask();
nTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
}
Post honeycomb you can specify to run async tasks in parallel
An AsyncTask should be started in the UI thread, not on the one doInBackground runs on. You could call publishProgress after every sleep, and spawn each AsyncTask in the resulting calls to onProgressUpdate, which run on the UI thread.
This is my code: (Some random text to complete question osdifhgsoid hgodfhgo hsdhoigifdshgnvfa oidvojd nobndisfn vbjobsf).
private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... urls) {
try{
Listen();
}
catch (Exception x)
{
textIn.setText("shit! " + x.toString());
}
long i = 10;
return i;
}
}
(Some random text again to complete question(stupid system) dpfgojd ipgsdigjsidoignsdog
public void Listen(){
int count = 0;
TextView msg = MyActivity.msg;
ServerSocket server;
Socket client;
try {
server = new ServerSocket(9797);
Log.d("My log", "server started");
Log.d("My log", "waiting for connnections");
while (started) {
try{
msg.setText("waiting for connection"); <=== here crashing
client = server.accept();
count++;
Log.d("My Log", "Connected");
Log.d("My Log", "aha" + count);
int i = 0;
String data = null;
byte[] bytes = new byte[1024];
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
while (is.available() == 0) {
try{
Thread.sleep(50);
}catch (Exception cc){}
}
is.read(bytes, 0, is.available());
os.write("hala".getBytes());
client.close();
}catch (Exception cc)
{
cc.toString();
}
}
} catch (Exception el) {
el.printStackTrace();
}
}
(Some random text to complete question). Please help
change it via the onPostExecute method!
The purpose of an AsyncTask is to do a long running task in a separate thread and then communicate the result back to the UI thread via onPostExecute().
Also, I'm not sure why you use Long as your return value since you do not seem to be using it. A much better solution would be to have Void as return value and save the exception and use that as an indicator if anything went wrong:
private class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
private Exception exception = null;
#Override
protected Void doInBackground(String... urls) {
try{
Listen();
}
catch (Exception x) {
exception = x;
}
}
#Override
public void onPostExecute(Void result) {
if(exception != null) {
textIn.setText("shit! " + exception.toString());
}
else {
// long running task was completed successfully
}
}
}
Yes, because you are trying to set the TextView inside the doInBackground() method, and this is not allowed.
So there is a solution if you want to set the TextView inside the doInBackground() method, do the UI updating operations inside the runOnUiThread method.
Otherwise, suggestion is to do all the UI display/update related operations inside the onPostExecute() method instead of doInBackground() method of your AsyncTask class.
Good idea would be to return a String in doInBackground(), say exceptionCatched. You can set it to Exception title in catch() block and then in onPostExecuted() just check if(!TextUtils.isEmpty(exceptionCatched)) textIn.setText(exceptionCatched); That's it!
private class DownloadFilesTask extends AsyncTask<Void, Void,Long>{
#Override
protected Long doInBackground(Void... params) {
publishProgress(progress);
//calculate progress and value from your downloading logic
try {
} catch (Exception e) {
return (long) 0;
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
//dis method run deafult on UI thread , so every time u publish ur onProgressUpdate will be called and update ur text here
}
#Override
protected void onPostExecute(Long result) {
super.onPostExecute(result);
if(result==0){
//error occured
}
}
// in case of exception return the result as long value to promt to onPostExceute()
I'm guessing runOnUiThread. You can't update the UI from any other thread than the UI thread.
I want to display a Progress Dialog while I have two threads running one after the other, but my data structure that I use gets populated via the threads, becomes null. Thus I used thread.get() method to wait for the thread to be finished....not sure how I can get around this here is an example of one of my Async Threads:
private void performDetailSearch(String reference) {
String addplus = searchterm.replace(" ", "+");
RestClientDS restpSd = new RestClientDS();
String url = PLACES_DETAILS_URL +"reference="+ reference + "&sensor=false&key=" + API_KEY;
Log.d("url",url);
String[] URL = {url};
restpSd.execute(URL);
try {
restpSd.get();
}
catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Use AsyncTask instead of Thread and call another task after one gets completed.
AsyncTask can be called this way new FetchData().execute();
private class FetchData extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage(getResources().getString(
R.string.Loading_String));
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
//do your background work
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
//call the another asynctask from here.
// new FetchData2().execute();
}
}
}