In my android application calling an API continuously in a loop then Progress Dialog make a shadow like appearance. I think the issue is that multiple dialog running..help me to avoid this shadow. Code given below:
for(int i = indexOfSelectedId + 1 ; i < photoall_id.size(); i++)
{
all_postid.add(photoall_id.get(i));
url = URLS.BASEURL + "mobile_api.php?action=post&post_id=" +posoall_id.get(i)+user_id="+userid;
new GetImage().execute(url);
}
private class GetImage extends AsyncTask<String, Void, ArrayList<String>> {
String json = null;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
all_data=new ArrayList<>();
dialog = new ProgressDialog(FullScreenActivity.this);
dialog.setMessage("Loading Image...");
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> aVoid) {
dialog.dismiss();
all_url.add(aVoid.get(0));
}
#Override
protected ArrayList<String> doInBackground(String... params) {
JSONReader reader = new JSONReader();
json = reader.getJsonGET(params[0]);
if (json != null) {
try {
JSONObject object = new JSONObject(json);
if (object.getJSONArray("posts").getJSONObject(0).getInt("count") != 0) {
photo_url = object.getJSONArray("posts").getJSONObject(0).getString("photo_url");
}
}
Suggest a solution.Thanks in advance
To avoid multiple dialog to show:
public void showProgress(String msg)
{
if(dialog == null){
dialog = new ProgressDialog(this);
dialog.setTitle(null);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
}
if(dialog.isShowing())
{
dialog.dismiss();
}
dialog.setMessage(msg);
dialog.show();
}
public void dismissProgress()
{
if(dialog != null && dialog.isShowing())
dialog.dismiss();
}
Related
I am implementing retrofit 2 in my app to call web services. My code is as below :
SignUp.java
ConnectionDetector connectionDetector = new ConnectionDetector(SignUpActivity.this);
if (connectionDetector.isConnectingToInternet()) {
ArrayList<HashMap<String, String>> arrayListCountryDetails = new ArrayList<>();
GetCountryList getCountryList = new GetCountryList();
arrayListCountryDetails = getCountryList.CallWebServiceForCountryDetails(this);
// The app should wait here till the above retrofit web service calling returns response
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(SignUpActivity.this, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
} else {
String message = "No internet connection.";
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(getResources().getString(R.string.app_name));
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
GetCountryList.java
public class GetCountryList {
ProgressDialog dialog;
APIService mAPIService;
ArrayList<HashMap<String, String>> arrayListCountryDetails;
public ArrayList<HashMap<String, String>> CallWebServiceForCountryDetails(final Context context) {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
arrayListCountryDetails = new ArrayList<>();
mAPIService = ApiUtils.getAPIService();
mAPIService.getCountryDetails().enqueue(new Callback<CountryDetailsResponseModel>() {
#Override
public void onResponse(Call<CountryDetailsResponseModel> call, Response<CountryDetailsResponseModel> response) {
if (response.isSuccessful()) {
HashMap<String, String> cntDetails = new HashMap<>();
cntDetails.put("airLineID", "0");
cntDetails.put("airLineName", "Select Airline");
arrayListCountryDetails.add(cntDetails);
// Get response
try {
if (response.body().getStatus() == 200 && response.body().getMessage().equalsIgnoreCase("success")) {
for (int count = 0; count < response.body().getCountry().size(); count++) {
cntDetails = new HashMap<>();
String countryID = response.body().getCountry().get(count).getCountryId();
String countryName = response.body().getCountry().get(count).getCountryName();
cntDetails.put("countryID", countryID);
cntDetails.put("countryName", countryName);
arrayListCountryDetails.add(cntDetails);
}
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
} else {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (Exception e) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
#Override
public void onFailure(Call<AirLineDetailsResponseModel> call, Throwable t) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
return arrayListCountryDetails;
}
}
When i am executing the code i am getting null pointer exception error as :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at com.abc.xyz.SignUpActivity.initializeScreen(SignUpActivity.java:176)
at com.abc.xyz.SignUpActivity.onCreate(SignUpActivity.java:147)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3278)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6912)
at java.lang.reflect.Method.invoke(Native Method)
I know that this is because the spinner initialization execution is takes place before retrofit response.
Please suggest me how can i wait for the retrofit response. What changes i need to do in above code. Please i am not able to move ahead due to this issue.
Thanks in advance.
Very roughly do something like the following. I just placed the necessary part of code inside the AsyncTask methods. Modify as necessary.
if (connectionDetector.isConnectingToInternet()) {
// The app should wait here till the above retrofit web service calling returns response
AsyncTask task = new AsyncTask<Void, Void, List<Map<String, String>>>() {
#Override
protected String doInBackground(Void... params) {
List<Map<String, String>> arrayListCountryDetails = new ArrayList<>();
GetCountryList getCountryList = new GetCountryList();
arrayListCountryDetails = getCountryList.CallWebServiceForCountryDetails(this);
return arrayListCountryDetails;
}
#Override
protected void onPostExecute(List<Map<String, String>> arrayListCountryDetails) {
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(SignUpActivity.this, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
task.execute();
}
Also remove any UI calls from your GetCountryList since this will be run on "background"
Pass Spinner object while loading data and set adapter after load complete
public class GetCountryList {
ProgressDialog dialog;
APIService mAPIService;
public void CallWebServiceForCountryDetails(final Context context,final Spinner spinnerCountryName) {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
final ArrayList<HashMap<String, String>> arrayListCountryDetails = new ArrayList<>();
mAPIService = ApiUtils.getAPIService();
mAPIService.getCountryDetails().enqueue(new Callback<CountryDetailsResponseModel>() {
#Override
public void onResponse(Call<CountryDetailsResponseModel> call, Response<CountryDetailsResponseModel> response) {
if (response.isSuccessful()) {
HashMap<String, String> cntDetails = new HashMap<>();
cntDetails.put("airLineID", "0");
cntDetails.put("airLineName", "Select Airline");
arrayListCountryDetails.add(cntDetails);
// Get response
try {
if (response.body().getStatus() == 200 && response.body().getMessage().equalsIgnoreCase("success")) {
for (int count = 0; count < response.body().getCountry().size(); count++) {
cntDetails = new HashMap<>();
String countryID = response.body().getCountry().get(count).getCountryId();
String countryName = response.body().getCountry().get(count).getCountryName();
cntDetails.put("countryID", countryID);
cntDetails.put("countryName", countryName);
arrayListCountryDetails.add(cntDetails);
}
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
//set Adapter
CountryDetailsAdapter countryDetailsAdapter = new CountryDetailsAdapter(context, arrayListCountryDetails);
spinnerCountryName.setAdapter(countryDetailsAdapter);
} else {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (Exception e) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
#Override
public void onFailure(Call<AirLineDetailsResponseModel> call, Throwable t) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
}
I have a GoogleTranslate.java file that has a class, GoogleTranslate, that extends AsyncTask. The purpose of this task is to perform Google translations.
I have another class, MyVocab, that allows the user to input a word to translate in an alert dialog. So on a click to the alert dialog button, the word will be translated to the desired language by calling on the GoogleTranslate class. However, when I pass a progress bar from MyVocab to GoogleTranslate it doesn't work. When the operation is running (for an observable amount of time), the progress bar doesn't show. I set the progress bar as VISIBLE in onPreExecute and set it as GONE in onPostExecute.
I'm wondering if it's because I have GoogleTranslate and MyVocab in two different java files since most of the examples I see have async class and the class that calls it in the same java file. Please let me know if there's anything I'm doing wrong that's causing this problem.
Here's the related code:
GoogleTranslate.java
public class GoogleTranslate extends AsyncTask<String, Void, String>{
private ProgressBar mProgressBar;
public GoogleTranslate(ProgressBar progressBar) {
super();
mProgressBar = progressBar;
}
#Override
protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
mProgressBar.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
String vocab = params[0];
String source = params[1];
String target = params[2];
String sourceQuery = "";
String targetQuery = "&target=" + target;
// "" means its
if (!source.equals("Detect Language")) {
sourceQuery = "&source=" + source;
}
try {
String APIKey = "MY_API_KEY";
String encodedQuery = URLEncoder.encode(vocab, "UTF-8");
URL url = new URL("https://www.googleapis.com/language/translate/v2?key=" +
APIKey +
"&q=" +
encodedQuery +
sourceQuery +
targetQuery);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally {
urlConnection.disconnect();
}
}
catch (Exception e) {
return null;
}
}
}
Parts of method from MyVocab:
protected void addVocabAlertDialog(final VocabDbHelper dbHelper, final String category,
final VocabCursorAdapter cursorAdapter) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Vocab");
LayoutInflater li = LayoutInflater.from(CategoryItem.this);
View promptsView = li.inflate(R.layout.alert_dialog_add_vocab, null);
final EditText vocabInput = (EditText) promptsView.findViewById(R.id.vocabInput);
final EditText definitionInput = (EditText) promptsView.findViewById(R.id.definitionInput);
final ProgressBar progressBar = (ProgressBar) promptsView.findViewById(R.id.progressBar);
builder.setView(promptsView);
final GoogleTranslate googleTranslate = new GoogleTranslate(progressBar);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String vocab = vocabInput.getText().toString();
String definition = definitionInput.getText().toString();
dbHelper.insertVocab(category, vocab, definition, 0);
if (!category.equals(VocabDbContract.CATEGORY_NAME_MY_WORD_BANK)) {
dbHelper.insertVocab(VocabDbContract.CATEGORY_NAME_MY_WORD_BANK, vocab, definition, 0);
}
// Update Cursor
Cursor cursor = dbHelper.getVocabCursor(category);
cursorAdapter.changeCursor(cursor);
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String vocab = vocabInput.getText().toString();
SharedPreferences sharedPreferences = getSharedPreferences("Translation", MODE_PRIVATE);
int sourcePos = sharedPreferences.getInt("Source", 0); // 0 is for Detect Language
int targetPos = sharedPreferences.getInt("Target", 19); // 19 is for English
String source = LanguageOptions.FROM_LANGUAGE_CODE[sourcePos];
String target = LanguageOptions.TO_LANGUAGE_CODE[targetPos];
final AlertDialog.Builder builder = new AlertDialog.Builder(CategoryItem.this);
builder.setMessage("Network is unavailable. Please try again later.");
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
if (isNetworkAvailable()) {
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab, source, target);
try {
String translatedJSON = asyncTask.get();
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
} catch (Exception e) {
dialog.show();
}
}
else {
dialog.show();
}
}
});
}
XML file that contains progress bar:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Vocab"
android:id="#+id/vocabInput"
android:inputType="textAutoComplete"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Definition"
android:id="#+id/definitionInput"
android:inputType="textAutoComplete"
android:layout_below="#+id/vocabInput"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="true"
android:id="#+id/progressBar"/>
I'd suggest using ProgressDialog instead.
I switched from ProgressBar because I faced a similar issue, even after programmatically creating one in the default constructor of my AsyncTask.
public class GoogleTranslate extends AsyncTask<String, Void, String> {
private ProgressDialog mProgressDialog;
private Context mContext;
public GoogleTranslate(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(
mContext,
"Please wait", // Title
"Translating", // Message
true // Indeteriminate flag
);
}
#Override
protected String doInBackground(String... params) {
...
}
#Override
protected void onPostExecute(String s) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
...
}
}
Call this AsyncTask like this:
new GoogleTranslate(getActivity() /* or getContext() */).execute(vocab, source, target);
Try to avoid the AsyncTask get() method and use a listener instead.
You should update your code this way:
1) In your googleTranslate class, add a listener:
private Listener listener;
public interface Listener{
void onTaskResult(String string);
}
public void setListener(Listener listener){
this.listener = listener;
}
and call it in your onPostExecute:
#Override
protected void onPostExecute(String s) {
if (listener!=null){ listener.onTaskResult(s); }
mProgressBar.setVisibility(View.GONE);
}
2) update your main class replacing the get with the listener management, replacing this:
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab, source, target);
try {
String translatedJSON = asyncTask.get();
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
} catch (Exception e) {
dialog.show();
}
with this:
googleTranslate.setListener(new GoogleTranslate.Listener() {
#Override
public void onTaskResult(String string) {
String translatedJSON = string;
JSONParser jsonParser = new JSONParser();
String translatedText = jsonParser.parseJSONForTranslation(translatedJSON);
definitionInput.setText(translatedText);
}
});
googleTranslate.execute(vocab, source, target);
I hope it helped.
add this before executing the googleTranslate :
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
AsyncTask<String, Void, String> asyncTask = googleTranslate.execute(vocab,source, target);
and also implement the onProgressUpdate in googleTranslate.
this link may help :
http://www.concretepage.com/android/android-asynctask-example-with-progress-bar
Try passing ProgressBar as constructor argument of GoogleTranslate class.
Add progress bar in your onPreExecute method and hide it in onPostExecute.
private class MyAsyncThread extends AsyncTask<Void, Void, String>
{
#SuppressWarnings("finally")
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
// your code
}
catch (Exception e) {
// TODO: handle exception
}
finally
{
return "OK";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(this, null, "Please wait....");
}
That's because you are blocking Main Thread by asyncTask.get() call, so no UI operations can run until asyncTask completes.
Remove this call and process the asyncTask's results in its onPostExecute(String s) and onCancelled() callbacks instead.
I have made an application in which user log's in his accounts.For this i have used asyncTask.Everything works fine but the thing is when i get the response i want the progress bar to stop.But it goes on continously.
Async Task
protected void onPreExecute() {
super.onPreExecute ();
CommonFunctions.showProgress (c, "Please Wait", true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute (s);
try {
JSONObject jsonObject = new JSONObject (s.trim ());
JSONObject NewDataSet = jsonObject.getJSONObject ("NewDataSet");
JSONObject Table = NewDataSet.getJSONObject ("Table");
String User_ID = Table.getString ("User_ID");
String Vendor_IEntity_Code = Table.getString ("Vendor_IEntity_Code");
String Vendor_Name = Table.getString ("Vendor_Name");
// setting the preferences
SettingPreference.setUserId (c, User_ID);
SettingPreference.setVendorId (c, Vendor_IEntity_Code);
SettingPreference.setVendorName (c, Vendor_Name);
} catch (JSONException e) {
e.printStackTrace ();
}
CommonFunctions.showProgress (c, "", false);
Crouton.makeText ((android.app.Activity) c, "Login Sucessful", Style.CONFIRM).show ();
}
#Override
protected String doInBackground(String... strings) {
response = HttpRequest.post ("https://beta135.hamarisuraksha.com/web/WebService/HsJobService.asmx/IsUserValid").send ("_UserID=" + strings[0] + "&_Password=" + strings[1]).body ();
Log.e ("Login Response", "" + response);
return response;
}
CommonFunctions
public class CommonFunctions {
private Context c;
public static void showProgress(Context context, String message, boolean isVisible) {
ProgressDialog progressDialog = new ProgressDialog (context);
progressDialog.setMessage (message);
progressDialog.setCancelable (false);
if (isVisible) {
progressDialog.show ();
} else if (isVisible == false) {
if (progressDialog.isShowing ()) {
progressDialog.dismiss ();
}
}
}
}
Problem:
ProgressDialog progressDialog = new ProgressDialog (context);
So each time you call the showProgress method you are creating a new ProgressDialog thus it is not dismissing upon calling the method again.
solution:
Create only once instance of ProgressDialog
public class CommonFunctions {
private Context c;
ProgressDialog progressDialog;
public static void showProgress(Context context, String message, boolean isVisible) {
if(progressDialog == null)
{
progressDialog = new ProgressDialog (context);
progressDialog.setMessage (message);
progressDialog.setCancelable (false);
}
if (isVisible) {
progressDialog.show();
} else if (isVisible == false) {
if (progressDialog.isShowing ()) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
}
Problem is your creating instance again without progressdialog show. So on second time
if (progressDialog.isShowing ())
above condition is false.
I would suggest you to use this approach, since these methods are provided there for a reason.
Start your Progressbar in onPreExecute() and simply stop it in onPostexecute().
new AsyncTask<Void, Void, Void>() {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(MyActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Your Message");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
};
#Override
protected Void doInBackground(Void... params) {
// Your Code
return null;
}
protected void onPostExecute(Void result) {
dialog.dismiss();
// UI updates if any
};
}.executeOnExecutor();
Try this way,hope this will help you to solve your problem.
public class CommonFunctions {
private static ProgressDialog progressDialog;
public static void showProgress(Context context, String message, boolean isVisible) {
if(progressDialog == null){
progressDialog = new ProgressDialog (context);
progressDialog.setMessage (message);
progressDialog.setCancelable (false);
}
if (isVisible) {
progressDialog.show ();
}else{
progressDialog.dismiss ();
}
}
}
In showProgress() you are creating new object. So when you are calling this method to hide progress bar it is creating new object and hiding new one not the previous one.
You need to update CommonFunctions class as following.
public class CommonFunctions {
private Context c;
ProgressDialog progressDialog;
public CommonFunctions(Context context){
this.c = context;
progressDialog = new ProgressDialog (context);
}
public static void showProgress(String message, boolean isVisible) {
progressDialog.setMessage (message);
progressDialog.setCancelable (false);
if (isVisible) {
progressDialog.show ();
} else if (isVisible == false) {
if (progressDialog.isShowing ()) {
progressDialog.dismiss ();
}
}
}
}
Use this as following:
CommonFunctions cf = new CommonFunctions(context);
to display progress use following:
cf.("Please Wait", true);
to hide progress use following:
cf.("", false);
I have a problem which I don't understand. I want to show a simple Progress Dialog in Android. So I created an AsyncTask and create the dialog in the constructor. I use the methods onPreExceution to initialise the dialog and the onPostExecute method I destory the dialog. So until now this looks total correct for me. But when I start the App on my Nexus 7 the dialog doesn't show up till the job is done. So it shows up for a half of a second at the end of the job... What am I doing wrong?
Thank you for your help ;)
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
public ParseHTMLCodeNew(Context context) {
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
UPDATE
This is my new AsyncTask:
public class ParseHTMLCodeNew extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private final OnCompleteTaskListener onCompleteTaskListener;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result){
onCompleteTaskListener.onComplete(result);
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
And i am calling it this way:
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
gData = data;
}
}).execute(url);
As i commented on your post, data has no value.
If you calling this code so:
String data = new ParseHTMLCodeNew(CommentActivity.this).execute(url).get();
Then you do not really see your dialogue because there is a blocking UI.
Method get() waits if necessary for the computation to complete, and then retrieves its result.
Call so:
new ParseHTMLCodeNew(CommentActivity.this).execute(url);
and the result of the work is handled directly in the AsyncTask.
If you need to transfer the data to the main thread, you should tell him that the task was completed.
Wat is the simple code, I just added OnCompleteTaskListener interface
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
private final OnCompleteTaskListener onCompleteTaskListener;
private ProgressDialog dialog;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
// einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
// your code here
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
sb.append(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
onCompleteTaskListener.onComplete(result);
}
}
And the example of a call
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
Toast.makeText(CommentActivity.this, data, Toast.LENGTH_LONG).show();
}
}).execute("your_url");
Be careful, this code can produce errors when you rotate your Phone.
When Activity destroyed but task is performed:
- progress dialog will close and will not open again
- local variable to dialog or context is incorrect.
If the operation is performed for a long time can make it through the of the services?
I've wrote a code that get data from online database and populate that data in lisview here is the part of my code hope that help !
class LoadMyData extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//Your code here
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// In my case use my adapter to display the data in a listview
adapter = new MyAdaper();
list.setAdapter(adapter);
}
});
}
}
Progress dialog should be shown from UI thread
runOnUiThread(new Runnable() {
public void run() {
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}});
Why am i getting this null pointer exception. Here is my code
I am getting the exception at OnProgressUpdate method after my first execution of publishProgress from doInBackground method
private class ScanVideoTask extends AsyncTask<String, Integer, String> {
private AsyncTaskCompleteListener<String> callback;
private Context context;
private String resultOutput;
private ProgressDialog mProgressDialog;
public ScanVideoTask(AsyncTaskCompleteListener<String> cb) {
this.callback = cb;
}
protected String doInBackground(String... args) {
// Get the URI of the video path & display it for a short period.
String filename = args[0];
int i= 0;
while(i < 1000000)
{
i++;
int progressPercentage = (int)(((float)i/(float)1000000) * (float)100);
publishProgress(progressPercentage);
}
return "ok";
}
protected void onProgressUpdate(Integer... progress) {
mProgressDialog.setProgress(progress[0]);
}
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
protected void onPostExecute(String result) {
System.out.println("on Post execute called" + result);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
callback.onTaskComplete(result);
}
}
Here is what in my onCreateDialog
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Scanning video..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
What am i missing?
The mProgressDialog of your ScanVideoTask seems to be never initialized.
Where do you launch your ScanVideoTask?
Modify your onPreExcecute method as described below :
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = new ProgressDialog(this);
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}