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);
}
Related
I am using an AsyncTask To show progress dialogue, the code is running as expected but the progress dialogue is still not showing up. Everything inside doInBackground is executing perfectly. I'm unable to understand what is causing this.
Async Task ->
class MyAsyncTask extends AsyncTask<String,String,String>{
ProgressDialog pd;
Context context;
PyObject object;
String str;
MyAsyncTask(Context contexted) {
this.context = contexted;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setMessage("This May Take Some Time");
pd.setTitle("Loading Tweet Engine");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String og = strings[0];
if(!Python.isStarted()){
Python.start(new AndroidPlatform(context));
Python py = Python.getInstance();
PyObject pyf = py.getModule("myscript");
object = pyf.callAttr("get_tweets",og);
}
else {
Python py = Python.getInstance();
PyObject pyf = py.getModule("myscript");
object = pyf.callAttr("get_tweets",og);
}
return object.toString();
}
#Override
protected void onPostExecute(String s) {
pd.dismiss();
super.onPostExecute(s);
}
}
And it is called by ->
String returnlist = new MyAsyncTask(this).execute(tempvalued).get();
how to get the result of the function void in asyntask
I've tried like this but the application always stops
I want to implement a progressbar in webview with asyntask when the waiting process
note: I've read this Webview with asynctask on Android
public class MainActivity extends AppCompatActivity {
EditText edInput;
Button btnCari;
WebView webView;
public String dataUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initEvent();
new asynCaller().execute();
}
private void initUI(){
edInput = (EditText) findViewById(R.id.editText);
dataUrl = edInput.getText().toString();
btnCari = (Button) findViewById(R.id.button);
webView = (WebView) findViewById(R.id.webview);
}
private void initEvent() {
btnCari.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String dataUrl = edInput.getText().toString();
dataUrl = dataUrl.isEmpty() ? "google" : dataUrl;
loadWebview("https://" + dataUrl + ".com");
message("Data link is "+dataUrl);
}
});
}
private void message(String pesan){
Toast.makeText(MainActivity.this,pesan, LENGTH_SHORT).show();
}
private boolean checkConnection(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
private void statusConnection(){
if (checkConnection()){
message("Device Online");
}else{
message("Device Offline");
}
}
private void loadWebview(String url){
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(url);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
}
public class asynCaller extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
// progressDialog.setMessage("Loading...");
// progressDialog.show();
message("persiapan");
}
#Override
protected Void doInBackground(Void... params) {
statusConnection();
if (checkConnection()) {
dataUrl = dataUrl.isEmpty() ? "google" : dataUrl;
loadWebview("https://" + dataUrl + ".com");
message("Data link is " + dataUrl);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// progressDialog.dismiss();
message("selesai");
}
}
EDITED
thank's for your help
i change a method doInBackground to onProgressUpdate for showing Webview and work and i get new problem with progress dialog, the progress dialog can't dismiss()
#Override
protected String doInBackground(String... params) {
publishProgress();
return url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
url = edInput.getText().toString();
progressDialog.show(MainActivity.this,"Pesan","Memuat . . .",true);
}
#Override
protected void onPostExecute(String result) {
if (progressDialog.isShowing()){
progressDialog.dismiss();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
loadWeb(url);
}
}
Change Your doInBackground() return type to String/int
public class asynCaller extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
// progressDialog.setMessage("Loading...");
// progressDialog.show();
message("persiapan");
}
#Override
protected String doInBackground(String... params) {
statusConnection();
if (checkConnection()) {
dataUrl = dataUrl.isEmpty() ? "google" : dataUrl;
loadWebview("https://" + dataUrl + ".com");
message("Data link is " + dataUrl);
}
return "Your Message";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// progressDialog.dismiss();
Log.d("Reached_postExe",result);
message("result");
}
}
The following is the code I would use, refactored from your own code. I have taken the liberty of making changes to your messaging to make it more meaningful in the console.
public class AsynCaller extends AsyncTask<Void, Void, String> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("AsynCaller.onPreExecute called");
// progressDialog.setMessage("Loading...");
// progressDialog.show();
message("AsynCaller.onPreExecute called");
}
#Override
protected String doInBackground(Void... params) {
System.out.println("AsynCaller.doInBackground called");
statusConnection();
final String result; // making it final forces it's definition whichever logic flow the code takes, which is good practice for a returned value
if (checkConnection()) {
dataUrl = dataUrl.isEmpty() ? "google" : dataUrl;
final String fullUrl = "https://" + dataUrl + ".com";
loadWebview(fullUrl);
result = "AsynCaller.doInBackground loadWebView called with " + fullUrl;
} else {
result = "AsynCaller.doInBackground checkConnection() is false");
}
// message(result); this is unnecessary as the Toast will appear due to the message() call in onPostExecute
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("AsynCaller.onPostExecute called");
// progressDialog.dismiss();
message(result);
}
}
I would, if I were you, replace the System.out calls with Log.d() so that the console output is only done in debuggable mode and not in any release version of your app. The reference for this is here Log
As a last suggestion I would not have the ProgressDialog being a property of the AsyncTask but instead call methods in MainActivity, as you have done with message() for instance. There are issues, for instance in this case, around possible memory leaks etc. if an object effectively holds a reference to an Activity context and the Activity is destroyed while the object continues to exist, as would be the case for a running AsyncTask.
I just wrote a code that need to show progress bar when ever interacting with server.but it is not working if i call dismiss method in below code.
public class AsyncClass extends AsyncTask<String, String, String> {
String result;
public ProgressDialog progressbar;
static Context context;
public AsyncClass(Context context,String result) {
this.context = context;
this.result = result;
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
URI u = new URI(params[0]);
// url = Urls.SENDMOVIE_REQUEST_URL;
HttpGet HG = new HttpGet(u);
HttpResponse response = httpclient.execute(HG);
//httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(response.getEntity());
Log.d("result", result);
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPreExecute() {
progressbar = new ProgressDialog(context);
progressbar.setCancelable(true);
progressbar.setMessage("loading....");
progressbar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressbar.setProgress(0);
progressbar.show();
}
#Override
protected void onPostExecute(String result) {
progressbar.dismiss();
}
}
I think its not showing because of progressbar.setProgress(0);
just remove it & try.
And If you want progressUpdates you need to do like this:
private class DownloadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
//Copy you logic to calculate progress and call
publishProgress("" + progress);
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Edited Iqbal's answer
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(){
dialog = new ProgressDialog(HomeActivity.this);
dialog.setCancelable(false);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
/** * Write your code */
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
// display UI
}
}
}
Use this below code it shall do the job for you
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
/** * Write your code */
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
// display UI
}
}
}
Edit:
Add the initialization of progress bar in the constructor as
public AsyncClass(Context context,String result) {
this.context = context;
this.result = result;
progressbar = new ProgressDialog(context);
}
And remove it from internecine().
I want to show the progressdialog when the webservice is called and stop the dialog on request is finished.
I did the following way but the dialog showing after the web service request is finished.
public class NetWorkRunTask extends AsyncTask<String, Void, String> {
Context ctx;
public NetWorkRunTask(Context ctx)
{
this.ctx=ctx;
mProgressDialog = new ProgressDialog(ctx);
}
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog.setMessage("Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
//contactService.getAssetsAtFirstRun();
// mProgressDialog.show();
return ServerConnection.getXmlRespFromUrl(params[0]); //this will include HttpPost
//return null;
}
#Override
protected void onPostExecute(String result) {
if(mProgressDialog != null)
{
if(mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}
}
and in onClickListener
String xml=null;
try {
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null).get();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
what's going wrong here.....
just do this in your asynk task
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
}
Remove the get() method, while calling your async task
change
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null).get();
to
xml =new NetWorkRunTask().execute(finalURL,null,null);
and
public class NetWorkRunTask extends AsyncTask {
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
//contactService.getAssetsAtFirstRun();
return ServerConnection.getXmlRespFromUrl(params[0]); //this will include HttpPost
}
#Override
protected void onPostExecute(String result) {
if(mProgressDialog != null)
{
if(mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}
In your code you are calling 'get()' method. [get() -waits if necessary for the computation to complete"].
Replace your Asynch task calling line with the below code and try
xml =new NetWorkRunTask(MyActivity.this).execute(finalURL,null,null);
You can define an interface in your Async task
public interface OnProcessCompleteListener{
public void onSuccess(String result);
public void onFailure();
}
and in your activity class you can implement the call back methods and can return results to the class.
OnProcessCompleteListener listener = listener = new OnProcessCompleteListener() {
#Override
public void onSuccess(String result) {
// do what u want
}
#Override
public void onFailure() {
}
};
Pass the 'listener' to the AsyncTask and call the onSuccess(String result), onFailure() methods where u want.
#Override
protected void onPostExecute(String result) {
if(result != null) {
listner.onSuccess(result);
}else{
listner.onFailure();
}
if(mProgressDialog != null){
if(mProgressDialog.isShowing()){
mProgressDialog.dismiss();
// uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
}
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();
}});