ProgressDialog not showing in AsyncTask - android

I am uploading some file to server using AsyncTask and I want to show a progress dialog in AsyncTask.
My AsyncTask is working fine and executing all the steps, but it never shows the dialog.I don't know what I have done wrong.
I have written below code but not working. Can someone help please!!!
Activity:
public class MainActivity extends AppCompatActivity {
ImageView videoImage ;
EditText editTextVideoTitle;
EditText editTextVideoDescription;
Button btnPostButton;
Button btnCancelButton;
private String mVideoPath;
private String mVideoThumb;
String strVideoTitle;
String strVideoDescription;
boolean videoPosted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_vid_with_desc);
editTextVideoTitle = (EditText) findViewById(R.id.videoTitle);
editTextVideoDescription = (EditText) findViewById(R.id.videoDescription);
btnPostButton = (Button) findViewById(R.id.postButton);
btnCancelButton = (Button) findViewById(R.id.cancelButton);;
mVideoPath = getIntent().getStringExtra("path");
mVideoThumb = getIntent().getStringExtra("thumb");
btnPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoPosted = postVideo();
if (videoPosted) {
Toast.makeText(getApplicationContext(), "Your video posted successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error in posting video, please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean postVideo() {
Log.i("Info", "PostVidWithDescActivity : postVideo : Start");
String strUserId = "";
String strReservedfield = "";
boolean isVideoPosted = false;
sharedPreferences = this.getSharedPreferences("com.app.rapid", Context.MODE_PRIVATE);
strVideoTitle = editTextVideoTitle.getText().toString();
strVideoDescription = editTextVideoDescription.getText().toString();
try {
strUserId = sharedPreferences.getString("userId", "");
strReservedfield = "ReservedField";
outputData = new PostToServerAsyncTask().execute(mVideoPath, strUserId, strVideoTitle, strVideoDescription, strReservedfield).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
if (null != outputData && outputData.equalsIgnoreCase("200")) {
isVideoPosted = true;
} else{
isVideoPosted = false;
}
return isVideoPosted;
}
private class PostToServerAsyncTask extends AsyncTask<String, Void, String> {
private String content;
private String Error = null;
private int serverResponseCode;
Context context;
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("inputBuilder","PostToServerAsyncTask : onPreExecute Start") ;
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(false);
//progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));
progressDialog.setCancelable(false);
progressDialog.show();
Log.i("inputBuilder","PostToServerAsyncTask : onPreExecute End") ;
}
#Override
protected String doInBackground(String... inputData) {
/*
File upload code
*/
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Some string";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("inputBuilder","PostToServerAsyncTask : onPostExecute Start") ;
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
}
Log.i("inputBuilder","PostToServerAsyncTask : onPostExecute End") ;
}
}
}

Could you please try this?
#Override
protected void onPreExecute() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(false);
//progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));
progressDialog.setCancelable(false);
progressDialog.show();
});
}
I think the general problem is in async task, which actually is on the separate thread

Related

Async Task error: no text is given when user had inserted a string

Solved: Could someone check my codes and help? I am using an emotion recognition API that generate strings from text input from user. I am learning to use AsyncTask to load the result but having an error showed "No text given" even when the user inserted a string at edittext, the error is detected from the 'catch' exception at the try{} block in doInBackground method.
public class Main3Activity extends AppCompatActivity {
private TextView textmain1, textmain2;
private EditText editText;
private Button submitBtn;
private String userInputText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textmain1 = (TextView) findViewById(R.id.detected3);
textmain2 = (TextView) findViewById(R.id.sentences3);
editText = (EditText) findViewById(R.id.edittext3);
submitBtn = (Button) findViewById(R.id.submitBtn3);
userInputText = editText.getText().toString();
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(userInputText);
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {
private String detectedResponse, sentencesResponse;
private ProgressBar progressBar;
#Override
protected void onPreExecute() {
progressBar = (ProgressBar) findViewById(R.id.progressbar);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected Boolean doInBackground(String... strings) {
String myString = strings[0];
try {
List<ToneScore> documentTones = new ArrayList<>();
List<SentenceAnalysis> sentenceDetectedTones = new ArrayList<>();
IamAuthenticator authenticator = new IamAuthenticator(authenticator);
ToneAnalyzer toneAnalyzer = new ToneAnalyzer("2020-02-22", authenticator);
toneAnalyzer.setServiceUrl(url);
ToneOptions toneOptions = new ToneOptions.Builder().text(myString).build();
ToneAnalysis toneAnalysis = toneAnalyzer.tone(toneOptions).execute().getResult();
documentTones = toneAnalysis.getDocumentTone().getTones();
if (documentTones == null || documentTones.isEmpty()) {
detectedResponse = "No tones are detected :(";
} else {
StringBuilder detectedTones = new StringBuilder();
for (ToneScore score : documentTones) {
if (score.getScore() > 0.5f) {
detectedTones.append(score.getToneName()).append(" \n").append(score.getScore()).append("\n\n");
}
}
detectedResponse = detectedTones.toString();
}
sentenceDetectedTones = toneAnalysis.getSentencesTone();
if (sentenceDetectedTones == null || sentenceDetectedTones.isEmpty()) {
sentencesResponse = "Oops! No sentence analysis is available for this one";
} else {
StringBuilder sentenceTones = new StringBuilder();
for (SentenceAnalysis sentenceAnalysis : sentenceDetectedTones) {
List<ToneScore> singleScoreBlock = sentenceAnalysis.getTones();
for (ToneScore toneScore : singleScoreBlock) {
if (toneScore.getScore() > 0.5) {
sentenceTones.append("\"").append(sentenceAnalysis.getText()).append("\"");
sentenceTones.append("\n").append(toneScore.getToneName()).append(": ").append(toneScore.getScore()).append("\n\n");
}
}
}
sentencesResponse = sentenceTones.toString();
}
} catch (ArrayIndexOutOfBoundsException | IllegalArgumentException | ServiceResponseException e) {
Main3Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Main3Activity.this, "API error here: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
publishProgress();
return true;
}
#Override
protected void onPostExecute(Boolean s) {
progressBar.setVisibility(View.GONE);
editText.setText("");
if (s.equals(true)) {
textmain1.setText(detectedResponse);
textmain2.setText(sentencesResponse);
} else {
Toast.makeText(Main3Activity.this, "Error :(", Toast.LENGTH_SHORT).show();
}
}
}
}
You have to get the text on click of the button
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userInputText = editText.getText().toString();
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(userInputText);
}
});

Wait for all the AsyncTask called in a loop are finished?

I'm calling async tasks in a loop on the onPostExecute() of an asyncTask. I want the control to wait until response of all the tasks is not receieved cause I'm collecting the response in a single arrayList which i have to pass a callback method after all the asyncTasks called in the loop are finished.
I'm avoiding to use the AsyncTask.get() as it blocks the main thread.
public class CallServerAsync extends AsyncTask<AsyncHttpRequestBo, Void, ArrayList<ArrayList<AsyncHttpRequestBo>>> implements PlatwareResponseListener {
PlatwareClientCommonUtils clientCommonFunctions;
Context context;
String url;
PlatwareResponseListener listener;
private ProgressDialog progressDialog;
ArrayList<AsyncHttpResponseBo> processResponseList = null;
ArrayList<AsyncHttpResponseBo> responseList = null;
public CallServerAsync(Context context, PlatwareResponseListener listener) {
this.context = context;
clientCommonFunctions = new PlatwareClientCommonUtils(context);
url = clientCommonFunctions.getServerUrlPrimary();
this.listener = listener;
responseList = new ArrayList<AsyncHttpResponseBo>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(context, "Please wait", "Downloading...");
}
#Override
protected ArrayList<ArrayList<AsyncHttpRequestBo>> doInBackground(AsyncHttpRequestBo... params) {
ArrayList<ArrayList<AsyncHttpRequestBo>> requestLists = clientCommonFunctions.generateRequestList(params);
return requestLists;
}
#Override
protected void onPostExecute(ArrayList<ArrayList<AsyncHttpRequestBo>> result) {
for (ArrayList<AsyncHttpRequestBo> httpRequestList : result) {
CallserverSubAsync callserverSubAsync = new CallserverSubAsync(context, this);
callserverSubAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, httpRequestList);
// ArrayList<AsyncHttpResponseBo> processResponseList = null;
// try {
// processResponseList = callserverSubAsync.get();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
}
listener.onAsyncTaskCompleted(responseList, listener);
progressDialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
progressDialog.dismiss();
super.onCancelled();
}
#Override
public void onAsyncTaskCompleted(ArrayList<AsyncHttpResponseBo> responseList, PlatwareResponseListener listener) {
if (listener instanceof CallServerAsync) {
processResponseList = responseList;
for (AsyncHttpResponseBo responseBo : processResponseList) {
this.responseList.add(responseBo);
}
}
}

Fetching data in AsyncTask

I am trying to pull data from Microsoft Azure with this method. The problem is that it can sometimes be really slow, and I need these data in the shared preferences to do anything else in the application. How can I create a loading dialog that will wait for the data to be fetched? I tried putting this method in the AsyncTask doInBackground() method, but the dialog would just appear and then disappear after a millisecond. What is the right way to do this? I was reading similar topics on stackoverflow, but never found a solution.
Thank you!
private class LoadViewTask extends AsyncTask<String, Void, Boolean>
{
private ProgressDialog dialog;
private MainActivity activity;
public LoadViewTask(MainActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
#Override
protected void onPreExecute()
{
//Create a new progress dialog
dialog = ProgressDialog.show(MainActivity.this,"Loading...",
"", false, false);
}
//The code to be executed in a background thread.
#Override
protected Boolean doInBackground(final String... args)
{
try
{
mClient.invokeApi("getsettings", jObj, new ApiJsonOperationCallback() {
#Override
public void onCompleted(JsonElement result, Exception error,
ServiceFilterResponse response) {
SharedPreferences settings = getSharedPreferences("SettingsPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
if (error != null) {
System.out.println("Error");
} else {
JsonObject res = result.getAsJsonObject();
try {
if(res.get("gender").toString().equals("null")){
userGender = res.get("gender").toString();
editor.putString("gender", userGender);
} else {
int index1 = res.get("gender").toString().indexOf("\"");
int index2 = res.get("gender").toString().lastIndexOf("\"");
editor.putString("gender", res.get("gender").toString().substring(index1+1, index2));
}
if(res.get("dob").toString().equals("null")){
userDob = res.get("dob").toString();
editor.putString("dob", userDob);
} else {
editor.putString("dob", res.get("dob").toString().substring(1, 11));
}
if (res.get("club").isJsonNull()) {
userClub = 0;
editor.putInt("userClub", userClub);
System.out.println("userclub is null in MA: "+userClub);
} else {
editor.putInt("userClub", res.get("club").getAsInt());
}
editor.commit();
} catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Boolean success)
{
//close the progress dialog
dialog.dismiss();
}
}
Just follow this steps
1) Create Method say loadDataFromServer() and put code inside
public void loadDataFromServer() {
dialog = ProgressDialog.show(MainActivity.this, "Loading...", "", false, false);
try {
mClient.invokeApi("getsettings", jObj, new ApiJsonOperationCallback() {
#Override
public void onCompleted(JsonElement result, Exception error, ServiceFilterResponse response) {
SharedPreferences settings = getSharedPreferences("SettingsPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
if (error != null) {
System.out.println("Error");
} else {
JsonObject res = result.getAsJsonObject();
try {
if (res.get("gender").toString().equals("null")) {
userGender = res.get("gender").toString();
editor.putString("gender", userGender);
} else {
int index1 = res.get("gender").toString().indexOf("\"");
int index2 = res.get("gender").toString().lastIndexOf("\"");
editor.putString("gender", res.get("gender").toString().substring(index1 + 1, index2));
}
if (res.get("dob").toString().equals("null")) {
userDob = res.get("dob").toString();
editor.putString("dob", userDob);
} else {
editor.putString("dob", res.get("dob").toString().substring(1, 11));
}
if (res.get("club").isJsonNull()) {
userClub = 0;
editor.putInt("userClub", userClub);
System.out.println("userclub is null in MA: " + userClub);
} else {
editor.putInt("userClub", res.get("club").getAsInt());
}
editor.commit();
dialog.dismiss(); // / DISMISS DIALOG HERE
} catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
2) Call this method like
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadDataFromServer();
}
3) dismiss dialog inside onCompleted() method. (I have added that line). just copy the method and call it.
Create a ProgressDialog and show() it before you call mClient.invokeApi and dismiss() it on onCompleted after you have done all the required processes
Try setting indeterminate to true,
//Create a new progress dialog
dialog = ProgressDialog.show(MainActivity.this,"Loading...",
"", true, false);

show progress dialog while loading data

I want to show a progress dialog while loading some data from remote server :
I'm using the following thread in order to get the data and it's working, but i'm not able to show the progress bar on the activity:
public class Request {
public String text ;
public boolean downloadText(String urlStr) {
final String url = urlStr;
new Thread () {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
Message msg = Message.obtain();
msg.what=2;
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
would you please tell me how can i do it !!
create the class as below and just call the object of this class.
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog Asycdialog = new ProgressDialog(ActivityName.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
Asycdialog.setMessage("Loading...");
Asycdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// do the task you want to do. This will be executed in background.
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Asycdialog.dismiss();
}
}
Use progressDialog
final ProgressDialog progress=ProgressDialog.show(youractivity.this,"","message");
new Thread()
{
public void run()
{
try{
youractivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
// your code
}
});
}
catch(Exception e)
{
}
progress.dismiss();
}
}.start()
Also, note that if you want to use Toast, you should use runOnUiThread
If you do not want to change the structure of your code, you can use runOnUiThread or an Handler to show and dissmiss the progress dialog. Show it when the firs line of the run method is excuted and dismiss it in the finally block.
public void run() {
runOnUiThread(new Runnable() {
public void run(){
// show progress dialog
}
});
/// your code here
try {
} catch (IOException e) {
} finally {
runOnUiThread(new Runnable() {
public void run(){
// dismiss progress dialog
}
});
}
}
Create Progress Dialog in AsyncTask
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
protected void onPostExecute(Void result) {
// do UI work here
}
}
pDialog = ProgressDialog.show(context, null, "Loading...", true);
pDialog.setCancelable(false);
new Thread() {
public void run() {
// handle the exception somehow, or do nothing
// run code on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
// do yor ui part here
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}.start();

Cannot show a ProgressDialog in AsyncTask

This is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.list);
new GetBlockListAsyncTask().execute(BlockListActivity.this);
}
public void initializeDialog() {
dialog = ProgressDialog.show(BlockListActivity.this, "", "Loading data. Wait...", true);
dialog.show();
}
public void dismissDialog(){
dialog.dismiss();
}
The GetBlockListAsyncTask:
public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String>{
private BlockListActivity callerActivity;
private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";
#Override
protected String doInBackground(Object... params) {
callerActivity = (BlockListActivity)params[0];
try {
Log.d(TAG, "Start to sleep");
Thread.sleep(4000);
Log.d(TAG, "End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
callerActivity.dismissDialog();
}
#Override
protected void onPreExecute() {
callerActivity.initializeDialog();
}
}
It will show error:
'Caused by: java.lang.NullPointerException'
onPreExecute(GetBlockListAsyncTask.java:101)
I find a solution is that if I move the initializeDialog out of the AsyncTask and put it before the line new GetBlockListAsyncTask().execute(BlockListActivity.this); in onCreate, it works.
The question is how to make it work if I want to put the initializeDialog in the AsyncTask .
Try adding a public constructor to your AsyncTask that accepts the Activity Context as the first argument:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a new AsyncTask with the Activity Context
AsyncTask task = new GetBlockListAsyncTask(this);
// Execute the task
task.execute();
}
public class GetBlockListAsyncTask extends AsyncTask<Object, Boolean, String> {
private Context activityContext;
private String TAG = "GetBlockListAsyncTask";
private String stringCode = "";
//Constructor
public GetBlockListAsyncTask(Context c) {
// Store the activity context
activityContext = c;
}
#Override
protected String doInBackground(Object... params) {
try {
Log.d(TAG, "Start to sleep");
Thread.sleep(4000);
Log.d(TAG, "End sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
activityContext.dismissDialog();
}
#Override
protected void onPreExecute() {
activityContext.initializeDialog();
}
}

Categories

Resources