0

Hi i have a function to get users from website database my function

private void get_users() {

    try {
        url = "my address";

        dbGetData3 = new DbGetData();
        new Thread(new Runnable() {
            public void run() {
                data = dbGetData3.getDataFromDB(url);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        userha = parseJSON3(data);
                    }
                });
            }
        }).start();

        Toast.makeText(context, "please wait ", Toast.LENGTH_LONG)
                .show();
    } catch (Exception e) {
        toast(9);
    }

Now i want add a loading progress bar while fetch data finished.

I use AsyncTask like this:

private class LongOperation extends AsyncTask<String, Void, String> {
    protected void onPreExecute() {

          progressDialog = new ProgressDialog(Login.this);
          progressDialog.setTitle("Processing...");
          progressDialog.setMessage("Please wait...");
          progressDialog.setCancelable(true); 
          progressDialog.show();

    }

    protected String doInBackground(String... params) {
        try {
            get_users();
        } catch (Exception e) {
        }
        return null;
    }

    protected void onPostExecute(String result) {
        progressDialog.dismiss();
    }
}

and i use this code for excute

        mytask = new LongOperation();
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
            mytask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        else
            mytask.execute();
        imageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                onCreate(savedInstanceState);
            }
        });

but progress dialog dose not show for me (get user worked)

i change my code like this:

if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
                mytask.onPreExecute();
                mytask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

            }
            else
            {
                mytask.onPreExecute();
                mytask.execute();
            }

then my progress dialog allways show

i test other code in stackoverflow like

AsyncTask doInBackground does not run

AsyncTask called from Handler will not execute doInBackground

Android SDK AsyncTask doInBackground not running (subclass)

but that not work for me please help me tankyou

Community
  • 1
  • 1

1 Answers1

0

Consdier using a LoaderManager and an AsyncTaskLoader for this sort of stuff.

AsyncTasks are a pain in the ass as because you have to manage their lifecycle with screen-rotations etc. With a LoaderManager all of that is in the past.

Below is an example of a loader which loads a list of "items".

public class ItemsLoader extends AsyncTaskLoader<List<Item>> {

private static final String TAG = "ItemsLoader";

private List<Item> mItems;
private ItemUpdatedReceiver mObserver;
private int mSomeParam;

public static class ItemUpdatedReceiver extends BroadcastReceiver {

    private static final String TAG = "ItemLoader";

    final ItemsLoader mLoader;

    public ItemUpdatedReceiver(ItemsLoader mLoader) {
        this.mLoader = mLoader;

        // listen for changes to the account we're using
        IntentFilter filter = new IntentFilter(GlobalConstants.ACTION_ITEMS_UPDATED);
        LocalBroadcastManager.getInstance(mLoader.getContext()).registerReceiver(this, filter);
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (GlobalConstants.ACTION_ITEMS_UPDATED.equals(action)) {

            mLoader.onContentChanged();
        }


    }
}

public void setSomeParam(int someParam){
    mSomeParam = someParam;
    onContentChanged();
}

public ItemsLoader(Context context, int someParam) {
    super(context);
    mSomeParam = someParam;
    onContentChanged();
}

@Override
public List<Item> loadInBackground() {

    // do whatever you need to do here

    ArrayList<Item> Items = new ArrayList<>();
    return Items;

}

/**
 * Called when there is new data to deliever to the client.
 *
 * @param data
 */
@Override
public void deliverResult(List<Item> data) {
    if (isReset()) {
        // an async query came in while the loader is stopped, we don't need the result
        //release resources if needed
        onReleaseResources(data);
    }

    List<Item> oldItems = mItems;
    mItems = data;

    if (isStarted()) {
        // If the Loader is currently started, we can immediately
        // deliver its results.
        super.deliverResult(mItems);
    }

    // At this point we can release the resources associated with
    // 'oldApps' if needed; now that the new result is delivered we
    // know that it is no longer in use.
    if (oldItems != null) {
        onReleaseResources(oldItems);
    }

}

@Override
protected void onStartLoading() {
    super.onStartLoading();
    if (mItems != null) {
        // If we currently have a result available, deliver it
        // immediately.
        deliverResult(mItems);
    }

    // start listening for changes
    if (mObserver == null) {
        mObserver = new ItemUpdatedReceiver(this);
    }

    if (takeContentChanged() || mItems == null) {
        // If the data has changed since the last time it was loaded
        // or is not currently available, start a load.
        forceLoad();
    }
}

/**
 * Handles a request to stop the Loader.
 */
@Override
protected void onStopLoading() {
    // Attempt to cancel the current load task if possible.
    cancelLoad();
}

/**
 * Handles a request to cancel a load.
 */
@Override
public void onCanceled(List<Item> items) {
    super.onCanceled(items);

    // At this point we can release the resources associated with 'profile'
    // if needed.
    onReleaseResources(items);
}

@Override
protected void onReset() {
    super.onReset();

    // Ensure the laoder is stopped
    onStopLoading();

// At this point we can release the resources if needed.
    if (mItems != null) {
        onReleaseResources(mItems);
        mItems = null;
    }

    // Stop monitoring for changes.
    if (mObserver != null) {
        LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mObserver);
        mObserver = null;
    }
}

/**
 * Helper function to take care of releasing resources associated
 * with an actively loaded data set.
 */
private void onReleaseResources(List<Item> data) {
    // For a simple List<> there is nothing to do.  For something
    // like a Cursor, we would close it here.

}
}

To use this class, in your activity you must extend LoaderManager.LoaderCallbacks> and override the methods:

 public Loader<List<Item>> onCreateLoader(int id, Bundle args) {
    // This is called when a new Loader needs to be created.  This
    // sample only has one Loader, so we don't care about the ID.
    // start the loading dialog here

    return new ItemsLoader(context);
}

public void onLoadFinished(Loader<List<Item>> loader, List<Item>data) {
    // do something with your data, hide the progress dialog
}

public void onLoaderReset(Loader<Cursor> loader) {
    // set the old data to null
}

To actually start loading:

getLoaderManager().initLoader(LOADER_ID, null, this);
JoeyJubb
  • 2,341
  • 1
  • 12
  • 19
  • Can i use this for get data from server and show a loading data progress dialog? – Ahmad Hashemi Aug 27 '15 at 11:56
  • When you use it from an activity or fragment, you have callbacks for when it's started and finished, so you can show your progress bar there. You can do whatever you like in the loadInBackground() method, including getting data from a server – JoeyJubb Aug 27 '15 at 11:58
  • Your activity or fragment will implement LoaderManager.LoaderCallbacks> When you're ready to load, call getSupportLoaderManager().initLoader(LOADER_ID, null, this) – JoeyJubb Aug 27 '15 at 12:00
  • how to use this class? – Ahmad Hashemi Aug 27 '15 at 12:10
  • i receive data with get_user() function. i want show a dialog while get_user work finished. – Ahmad Hashemi Aug 27 '15 at 12:26
  • I've edited my answer to show a complete example. You can use this from fragments too (doesn't have to be an activity) – JoeyJubb Aug 27 '15 at 12:42