I'm using volley to fetch data using volley and display in User Interface, and it takes time to load the data. What i want to happen is, I want to fetch the data in background during the splash screen or loading screen and display it in User interface. I want the fetching part to be done in another activity and it should be a background service and this should be called in "main activity" to populate the fields.
You can try using the AsyncTask. So the process goes like that:
In onPreExecute() you can show a ProgresDialog or a ProgresBar to visualize your loading process
in doInBackground(Params...) you start loading your data
and in onPostExecute(Result) you display your data in UI and hide your ProgresDialog/ProgresBar.
Example of AsyncTask usage.
Do it like this:
private class LoadDataBaseData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Start loading your data
return "Data loaded";
}
#Override
protected void onPostExecute(String result) {
//Update your UI with data you loaded/start your activity with loaded data
}
#Override
protected void onPreExecute(){
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
use AsyncTask like that
private class LongOperation extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
//do your work here
return "Executed";
}
#Override
protected void onPostExecute(String result)
{
progressBar.dismiss();
}
#Override
protected void onPreExecute()
{
progressBar = ProgressDialog.show(getActivity(), null, "message...");
progressBar.show();
}
#Override
protected void onProgressUpdate(Void... values)
{
}
}
Related
I am using an AsyncTask in an activity.
here is my code
public class MyActivity extends AppCompatActivity {
EditText editUserNameLogin;
EditText editPassLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//ButterKnife.bind(this);
editUserNameLogin = (EditText) findViewById(R.id.input_username_login);
editPassLogin = (EditText) findViewById(R.id.input_password_login);
}
public class AsyncTaskClass extends AsyncTask<String, String, String> {
String strUserName = editUserNameLogin.getText().toString();
String passLogin = editPassLogin.getText().toString();
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
Toast.makeText(MyActivity.this, passLogin, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String r) {
}
}
but in doInBackground can't get values passLogin or strUserName
(Toast.makeText(MyActivity.this, passLogin,) don't show any text)
Try and execute AsyncTaskClass in onCreate
new AsyncTaskClass().execute(); //use this method and call this in onCreate
Try this one, inside onCreate
String response="checking";
new AsyncTaskClass().execute(response);
then create inner class AsyncTaskClass,
private class AsyncTaskClass extends AsyncTask<String,Void,String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String respose1 = strings[0];
return respose1;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);}
}
You can not perform UI operation inside background AsyncTask doInBackground method because AsyncTask not work with current UI thread, its create new thread while you initialize and execute.
Let me explain you in bref.
While activity start its stay with Activity Thread and when you complete activity operation and destroy its completely remove from operation task.
But while you start AsyncTask on Activity its start with individual operation stat that not depends on activity that you start, so if you perform UI operation in doInBackground method and in case Activity destroyed and you working on UI that already destroyed by activity and UI cannot get reference, its generate an exception. So it's necessary to work with current activity thread not another background thread.
There are many case that you can pass data inside AsyncTask, i'm comfortable with below operation, it can help you also.
// Pass data to AsyncTask comma separated values
new MyBackgroundTask().execute("Hello there!","How are you?");
private class MyBackgroundTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... strings) {
String message1 = strings[0];
String message2 = strings[1];
Log.d("_TAG_", "First String: " + message1);
Log.d("_TAG_", "Second String: " + message2);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
For more information read Android Official Documents AsyncTask Developer Guides
You cant show ui operations like toast in doInBackground if you still want to do that then use this code to display toast while in doInBackground
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
});
and also you need to call yourAsyncTaskObject.execute to start asynctask
I have no idea what exactly you want to achieve by such behavior.
But i am pointing out some point here . First of all you can not access any UI element in background thread .
#Override
protected String doInBackground(String... params) {
Toast.makeText(MyActivity.this, passLogin, Toast.LENGTH_SHORT).show();
}
The above code is not going to work as doInBackground runs asynchronously separate from UI thread.
If you want to show a toast on AsyncTask started then do it in onPreExecute or after execution do it in onPostExecute.
#Override
protected void onPreExecute() {
Toast.makeText(MyActivity.this, passLogin, Toast.LENGTH_SHORT).show();
}
And as i see you never execute the AsyncTask then how are you expecting anything from it. Do call execute().
new AsyncTaskClass().execute();
For more on AsyncTask read AsyncTask.
Try the following:
#Override
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MyActivity.this, passLogin, Toast.LENGTH_SHORT).show();
}
});
}
AsyncTask enables proper and easy use of the UI thread. This class
allows you to perform background operations and publish results on the
UI thread without having to manipulate threads and/or handlers.
new AsyncTaskClass("SEND STRING").execute();
You can pass this Your Value this way
private class AsyncTaskClass extends AsyncTask<String, String, String> {
String strRESPONSE="";
public MyAsyncTask(String str_GET) {
this.strRESPONSE=str_GET; // print "SEND STRING"
}
}
i have designed custom gallery but problem is that every time when i open gallery asyctask is call and all image getting load again. i want to load asyctask if new images arrived into device otherwise directly gallery will be shown without load
i have no more idea that how to do this kind of programming stuff so if there is anyway to do this kind of stuff then please suggest me
is there any way to do this ... ??
private class AsyncTaskForListview extends
AsyncTask<String, String, String> {
private String responce;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
getAllGalleryFolderName(); // process for get image
return responce;
}
#Override
protected void onPostExecute(String result) {
lvShowAllImageFolder.setAdapter(effectImageAdapter); // set adapeter in listview
effectImageAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog
.show(DisplayGalleryActivity.this,
getResources().getString(
R.string.progress_dialog_heading),
getResources().getString(
R.string.progress_waiting_message));
}
#Override
protected void onProgressUpdate(String... text) {
}
}
You can use the FileObserver class to monitor a file or fold. It will notify if a change by any process in the device occurs. More details here .
I'm using an AsyncTask to download the data from the server and I want to insert the data into my database. Where do I have to put the insertion code and how can I stop the AsyncTask from inserting data if the user presses the Home button?
I'm currently using asynctask.cancel(true) but I can't stop the database insertion.
public class TalkToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
//download data from the server
return something;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// dismiss dialog
}
}
The best option would be to do the database insertion operation in onPostExecute().
If the AsyncTask is cancelled, then onPostExecute() will not be invoked.
From The Documentation for AsyncTask.cancel():
Calling this method will result in onCancelled(Object) being invoked
on the UI thread after doInBackground(Object[]) returns. Calling this
method guarantees that onPostExecute(Object) is never invoked. After
invoking this method, you should check the value returned by
isCancelled() periodically from doInBackground(Object[]) to finish the
task as early as possible.
You could also add a check to isCancelled() in your doInBackground() method.
#Override
protected String doInBackground(String... params) {
//download data from the server
if (isCancelled()){
//Prevent data from being inserted in the database
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
//Dismiss ProgressDialog
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return something;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// dismiss dialog
//Insert data into database
}
First of all you start downloading the db from server inside doInBackground(String... params)
Then inside onPostExecute(String result) method write your DB insertion logic and at the end of it close your database.
Finally finish your activity if user presses Home button (it will automatically cancel your AsyncTask)
Hope it make sense ...
Create new class which contains data insertion function.
Ex -
//create new class
public class DBInsert(){
//write data insertion login in this function.
public string insertData(){
......
......
}
}
//your async task.
public class TalkToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
//download data from the server
//Call db insert function.
DBInsert.insertData();
return something;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// dismiss dialog
}
}
I have a progress bar and I do not want to incorporate a numerical value to show the loading of some content. I just want that the ProgressBar should appear, animate and then go away.
I used:
public void buttonClick(View v){
ProgressBar mProgress=(ProgressBar)findViewById(R.id.my_progress);
mProgress.setVisibility(VISIBLE); //line 1..
//loading data from web... takes time
mProgress.setVisibility(INVISIBLE); //line 2..
}
but when I run this code, both line 1 and line 2 executes, but the UI changes afterwards, which is not desired. I want that when the button is clicked, the progress bar should appear and when the data is downloaded from the web the progress bar should disappear.
I tried setting the visibility from another thread, but it didn't work as UI changes are not allowed in other threads.
You download your data in AsyncTask right? Put this code
private class DownloadData extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// download your data here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mProgress.setVisibility(View.GONE);
}
}
The best way implement it by using an AsyncTask
MyTask.java
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
Context context;
MyTask(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
dialog=new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
//do your task here
}
#Override
protected void onPostExecute(Void result) {
if(dialog.isShowing()){
dialog.dismiss();
}
}
}
You can start the task like this:
public void buttonClick(View v){
new MyTask(YourActivity.this).execute();
}
You can modify the AsyncTask accordingly to retrieve the result.
Hope it helps. :)
I am working on an android app, in that app i have intent2 which on click redirects to intent3 and takes some time then loads a table and displays server data into it.
Sometimes if there is a lot of data, it tales pretty much time to get the dataload and the time blank screen is displayed increases.
i wish to show a loading bar till the data loads.
how can i show the ProgrssBar till only when data is not displayed ?
Probably your best bet would be to use AsyncTask in your "intent3":
You could do it like this:
private class performBackgroundTask extends AsyncTask <Void, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(ClassName.this);
protected void onPreExecute()
{
Dialog.setMessage("Please wait...");
Dialog.show();
}
protected void onPostExecute(Void unused)
{
try
{
if(Dialog.isShowing())
{
Dialog.dismiss();
}
// do your Display and data setting operation here
}
catch(Exception e)
{
}
#Override
protected Void doInBackground(Void... params)
{
// Do your background data fetching here
return null;
}
}
You probably need to run an AsyncTask on onCreate when you open the new activity, the structure of the asynctask would be like this (taken from the google doc), notice that if you want to increament a progress bar you have to implement onProgressUpdate and call publishProgress in the doInBackground method
private class DownloadFilesTask extends AsyncTask<Void, Integer, Void> {
protected void onPreExecute()
{
// show your progress bar
}
protected Void doInBackground(Void... params) {
// do your work and publish the progress
publishProgress(progress);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Void result) {
//dismiss your progress bar
}
}
This code is just an example, of course you need to adapt it to your logic/code.
Check out this simple and complete example