I got some trouble using the asynctask to query in my cloud database.
Due the response delay to query I cant get the result correctly. Getting NULL.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
this.mBox = new Box();
super.onCreate(savedInstanceState);
setContentView(R.layout.novomenu_layout);
InicializaAzure(); // init connection to azure mobile service
this.mPalletDao = new PalletDAO(this);
this.mBoxDao = new BoxDAO(this);
mBox = mBoxDao.AzureGetBoxById(1); // query the cloud database
}
BoxDAO.java
public Box AzureGetBoxById(final long id){
final Box[] box = new Box[1];
final boolean[] flag = {false};
new AsyncTask<Void, Void, Void>() {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
final MobileServiceList<Box> result = mBoxTable.where().field("id").eq(id).execute().get();
Box mBox = result.get(0);
box[0] = mBox;
} catch (Exception exception) {
//createAndShowDialog(exception, "Error");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
flag[0] = true;
}
}.execute();
return box[0];
//return null;
}
I am getting always NULL until the asynctask has finished. but I need the result in the same time.
How can I solve that? I've searched about asynctask but I didnt find anything like this.
Thank you.
Your code is correct, and it works fine. However, if you want to get the result to show in the same time of UI displayed, you can not solve it easily by using the asynctask.
Per my experience, there are two ways can help solve that.
Remove the asynctask code and use the sync method to get data, but it will cause UI hang so that it not be recommended.
Use MobileServiceSyncTable to enable offline sync to solve it.
There is a sample doc https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-get-started-offline-data/ to help adding offline data sync into your app.
You alse can watch some vedio to learn it, please move to http://channel9.msdn.com/Shows/Cloud+Cover/Episode-155-Offline-Storage-with-Donna-Malayeri and http://azure.microsoft.com/documentation/videos/azure-mobile-services-offline-enabled-apps-with-donna-malayeri/.
Related
I have the following code. My problem is, that I can't get the JSON.execute() to stop/cancel. I spend quite some time looking up possible answers but I wasn't able to find anything that really worked (e.g. JSON.cancel(true)). As soon as I turn the trackerswitch on, the AsnycTask starts running every 3 seconds just like it's supposed to. Is there a way to easily stop the AsyncTask from executing as soon as the trackerswitch is turned off?
private boolean tracking = false;
private Switch trackerswitch;
private final Timer timer= new Timer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.table_layout);
final Handler handler=new Handler();
final int delay = 4000;
trackerswitch=findViewById(R.id.trackerswitch);
trackerswitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NetworkAccess JSON = new NetworkAccess();
if(trackerswitch.isChecked()){
trackerswitch.setText("Tracking...");
tracking=true;
handler.postDelayed(new Runnable() {
#Override
public void run() {
NetworkAccess JSON = new NetworkAccess();
JSON.execute();
handler.postDelayed(this, delay);
}
},delay);
}
else{
tracking=false;
trackerswitch.setText("Start Tracking");
}
}
});
}
}
This is what's called in the network class:
public class NetworkAccess extends AsyncTask<Void, Void, Void> {
public ArrayList<String> alldata = new ArrayList<>();
public ArrayList<String> locationlist = new ArrayList<>();
int stride;
String data;
#Override
protected Void doInBackground(Void... voids) {//4B4ADC
SOME CODE WHICH ISN'T IMPORTANT FOR MY PROBLEM
alldata.addAll(elementlist);
locationlist.addAll(loctrack);
}
}
catch(IOException | JSONException e){
MainActivity.field1.setText(e.getClass().getCanonicalName());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.field1.setText(String.format("%20s %20s", alldata.get(0), alldata.get(1)));
COUPLE MORE OF THESE SETTEXT COMMANDS TO FILL A TABLE WITH DATA
}
}
Thanks for your help!
handler.postDelayed() adds objects of the Runnable you provide to the message queue, to be run at the specified interval. You need to remove all the queued objects from the message queue in order to cancel the execution. Calling JSON.cancel(true) does not affect other objects that are already added to the queue.
You'll have to retain a reference to your Runnable implementation and then call handler.removeCallbacks(r) to prevent further executions. Instead of using an anonymous class in handler.postDelayed().
This documentation page sheds more light on the matter.
Also refer this page for what happens when you call cancel(true) on an AsyncTask.
So I'm just trying to create an Alert Dialog that is just a message (no buttons or titles). I want to display an alert dialog when a background task is running. The alert dialog will run on the UI thread.
Here's what I have done so far:
protected void onPreExecute() {
super.onPreExecute();
AlertDialog altDlg;
altDlg = new AlertDialog.Builder(AlertDialogActivity.this).create();
altDlg.setMessage("Retrieving Information. Please Wait");
altDlg.show();
}
I also tried doing this:
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("Retrieve Info. Please Wait").show();
The error I am getting with the first one is:
cannot find symbol 'AlertDialogActivity'
symbol: class AlertDialogActivity
location: class com.example.Device.Activity
The second attempt error says:
incompatible types: com.example.Device.Activity cannot be converted to android.content.Context
I'm not sure what I am doing wrong in either scenario. I just want to display a basic message when a background task is running and I was hoping the closest thing I can use is AlertDialog.
EDIT for how to set up AsyncTask properly:
Small background of what I want to do. I just want to read in a file, deserialize it and save it's contents to a db.
Right now I'm assuming I only need two activities.
One is my main activity:
public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup);
final Button setup_button = (Button) findViewById(R.id.setup_button);
setup_button.setOnClickListener (new View.OnClickListener() {
public void onClick(View view){
setContentView(R.layout.retrieve_info);
}
});
}
}
Now the onClick event just moves to the new view that is supposed to display the message or alert dialog that says retrieving information. Please Wait. It displays the message while reading a file and saving to db. Once the file is read and saved, The message should disappear and say something like setup complete.
My second activity so far is:
public class RetrieveInfoActivity extends AsyncTask<Void,Void,Void> {
private ProgressDialog progressBar;
private void retrieveInfo(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
//Read all the lines until there are no more lines
while (scanner.hasNextLine()) {
scanner.nextLine();
//TODO: deserialize and save to db
}
scanner.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
}
#Override
protected Void doInBackground(Void... params) {
retrieveInfo("test.txt");
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage("Retrieve Information.Please wait");
progressBar.show();
}
#Override
protected void onPostExecute() {
progressBar.dismiss();
}
}
That's all I really have so far. I just need to understand how to set up this in Android conceptually.
Hope this makes sense.
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Instead of using an AlertDialog use a ProgressBar, it will do the trick for you.
private ProgressDialog progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage("Your message");
progressBar.show();
}
#Override
protected void onPostExecute(final String error_code) {
progressBar.dismiss();
}
Looks like you are extending AsyncTask and trying to use it as a context. That won't work as AsyncTask itself is nothing but an abstract class.
You need to create a custom constructor for your AsyncTask to fetch the Context:
public class MyTask extends AsyncTask<Void, Void, Void> {
private Context mCtx;
public MyTask(Context context) {
mCtx = context;
}
...
Then when starting your AsyncTask, pass the context:
new MyTask(this).execute();
Another way would be to make the AsyncTask an inner class and use YourActivity.this when creating the dialog. Example:
public class YourActivity extends Activity {
...
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
AlertDialog dialog = new AlertDialog.Builder(YourActivity.this).create();
}
#Override
protected Void doInBackground(Void... params) {
...
}
}
}
I am using this code to load data from online database to my android application .
I am wondering what can i add to make this code better ?
Sometimes the progress dialog keeps spinning and never gets the data, the application is stuck then, any ideas on how i can prevent that ?
class LoadAllSections extends AsyncTask<String, String, String>
{
// make a progress dialog appear with the selected specifics
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading all sections, please wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// in the background run this code to retrieve data from the server
protected String doInBackground(String... args)
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_Sections,"POST", params);
try
{
int success = json.getInt(TAG_SUCCESS);
sections = json.getJSONArray(TAG_SECTIONS);
if (success == 1)
{
for (int i = 0; i < sections.length(); i++)
{
JSONObject c = sections.getJSONObject(i);
section_id = c.getString(TAG_SECTION_ID);
section_name = c.getString(TAG_SECTION_NAME);
section_desc = c.getString(TAG_SECTION_DESC);
section_image = c.getString(TAG_SECTION_IMAGE);
section_valid = c.getString(TAG_SECTION_VALID);
HashMap <String,String> sectionmap = new HashMap<String,String>();
sectionmap.put(TAG_SECTION_ID, section_id);
sectionmap.put(TAG_SECTION_NAME, section_name);
sectionmap.put(TAG_SECTION_DESC, section_desc);
sectionmap.put(TAG_SECTION_IMAGE, section_image);
sectionmap.put(TAG_SECTION_VALID, section_valid);
sectionlist.add(sectionmap);
}
}
else
{
finish();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
// disable the progress dialog and load data to the gridview
protected void onPostExecute(String file_url)
{
pDialog.dismiss();
adapter=new SectionAdapter(MainActivity.this,sectionlist);
SectionsGridView.setAdapter(adapter);
}
}
I wanted to add a comment, but I am not allowed to.
Don't have enough reputation :-(
Pass url_section as argument to doInBackground instead of making it global.
I would place the httpRequest insde a try catch block.
Did you set the timeout, if the httpRequest is not answering? I would set that to
60 seconds. I think by default this is set to 600 seconds.
Why do you pass the file_url to onPostExecute instead of passing the
sectionList?
Take a look at AsyncTask. If you don't want to pass anything between the methods, you can also use Void. So in your case AsyncTask would also do it.
I am encountering a problem in my Android application. I am creating a currency converter. I need to create a progressdialog that appears when you convert a value from one currency to another.
Here is part of my code:
if (text1.equals("US Dollar - USD") && text2.equals("Euro - EUR") && edittextdollars.length() > 0 && edittexteuros.length()==0) {
dialog1 = ProgressDialog.show(getActivity(), "", "Calculating...");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
convertvalues("USD", "EUR");
handler.sendEmptyMessage(0);
}
catch (Exception e) {
edittexteuros.setText("Error");
}
}
});
thread.start();
}
private Handler handler = new Handler () {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
dialog1.dismiss();
break;
}
}
};
The progressdialog comes up and goes away, but nothing happens in the background. Here are a few pics of what my app looks like:
This is before the progressdialog comes.
When I press calculate:
After the progressdialog finishes:
As you can see, after the progressdialog goes away, my values don't convert.
In my code,
convertvalues("USD", "EUR");
just gets actual currency value from the internet and multiplies it with the value in my edittext. There is nothing wrong with it and it worked without the progressdialog. I have tested it many times myself.
What am I doing wrong here? I have checked Google for over a week, but I could not find a single solution. Any help regarding this problem is greatly appreciated.
Just like how you update your progressdialog in a handler, you must also update EditTexts in the handler (as it must run on the UI thread). So ideally you would return the result from convertvalues and then pass it to the handler via a message.
From what I can see, your code is fine but you aren't updating the TextView/EditText values when you dismiss the dialog. This means that although it looks like nothing is happening, it actually is - you just aren't updating to see the results.
So, assuming convertvalues() has the converted values stored somewhere, before you call dismiss() you should set your TextViews based on those values.
you can use asynctask in android
see following code may be it will help you..
private class asyncTask extends AsyncTask<Void, Void, Boolean>
{
Context context;
ProgressDialog pd;
asyncTask(Context context)
{
this.context = context;
pd = new ProgressDialog(activityContext);
}
protected void onPreExecute()
{
pd.setTitle("Loading..");
pd.setMessage("Please wait ...");
pd.setCancelable(false);
pd.show();
}
protected void onPostExecute(Boolean result)
{
if(pd.isShowing()) pd.dismiss();
}
#Override
protected Boolean doInBackground(Void... params)
{
convertvalues();
return boolean_value;
}
}
And Just Call this asynctask with
new asyncTask(Your_Context).execute();
My app loads a lot of stuff on startup and after testing it delays too long at the beginning to not have a splash screen. So, I want to display a splash screen until my app is done loading. I do NOT want to display a screen with a timer for X seconds. I found an example here:
Android SplashScreen
I tried implementing the code in the SO topic above but I just don't understand the code. After integrating it in my code I come up with one error that I commented into the code below. But I don't understand a lot of the code and I have commented in the code below the parts I am confused by.
public class MainMenu extends Activity {
private ProgressDialog pd = null;
private Object data = null; //What is this?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainmenu);
// show the ProgressDialog on this thread
this.pd = ProgressDialog.show(this, "Working...", "Downloading data...", true, false);
// start a new thread that will download all the data
new DownloadTask().execute("Any parameters to download."); //What is DownloadTask()?
}
private class DownloadTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args) { //Are these parameters correct?
return "replace this with your object"; //What is this?
}
protected void onPostExecute(Object results) {
// pass the resulting data to the main activity
MainMenu.this.data = result; //Error: "result cannot be resolved to a variable"
if(MainMenu.this.pd != null) {
MainMenu.this.pd.dismiss();
}
}
}
}
Let's start with the error:
MainMenu.this.data = result;
Notice the typo? It should be result*s*:
MainMenu.this.data = results;
Addressing the rest of your questions below:
private class DownloadTask extends AsyncTask<String, Void, Object>
The declaration is for an inline class called DownloadTask, and it states that you'll be taking Strings (via String...) as parameters to your doInBackground(String... params).
The second parameter (Void in your case) indicates the datatype used to "publish" the progress via publishProgress(DATATYPE)/onProgressUpdate(DATATYPE... progress). This method is suitable for notifying the user of changes, for example when you've finished downloading a file but still have a few to go.
The last parameter (Object), indicates what type of data you'll be passing on to onPostExecute(DATATYPE), in this example Object. This could either be to update a ListAdapter somewhere, or trigger any other UI change based on the outcome of the actions done in doInBackground.
Show ProgressDialog in onPreexecute and dismiss it in onPostExcute methods
something like this
private class DownloadTask extends AsyncTask<String, Void, Object> {
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(activity);
mProgressDialog =ProgressDialog.show(activity, "", "Please Wait",true,false);
super.onPreExecute();
}
protected Object doInBackground(String... args) { //Are these parameters correct?
return "replace this with your object"; //What is this?
}
protected void onPostExecute(Object results) {
// pass the resulting data to the main activity
MainMenu.this.data = results; //it should be results
if (mProgressDialog != null || mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
if(MainMenu.this.pd != null) {
MainMenu.this.pd.dismiss();
}
}