progress dialog with asynctask
Asked Answered
A

2

5

i have 3 classes and the class called WebServiceCleint class is extending Asynctask and in doInBackgrnd() i m passing url and i m getting data from webservice. but i m calling this from another class's method called VerifyTeacherId. Now how can i show progress dialog??? where should i write the pg.show and pg.dismiss.???

public  class WebServiceClient extends AsyncTask<String, Void, String>
{

 private static final String base_path = "http://www.gdaschools.in/";
 protected static final String SLASH = "/";


 private ProgressDialog dialog;
 private Activity activity;

 public WebServiceClient(Activity activity) {
        this.activity = activity;
        this.dialog = new ProgressDialog(activity);
    }

    @Override
     protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }



@Override
protected String doInBackground(String... params) {

    StringBuffer sb = new StringBuffer();
    sb.append(base_path);
    sb.append(params[0]);
    HttpRetriever retrieveResponse = new HttpRetriever();
    retrieveResponse.retrieve(sb.toString());
    return retrieveResponse.getResponseXml();
}



 @Override
protected void onPostExecute(String result) {
     if (this.dialog.isShowing()) {
           this.dialog.dismiss();
     }
}
}

And the method where i m calling is it in another class named SelectOptionActivity. The method is

public void verifyTeacherId(View view)
{
    teacherIdString = TeacherId.getText().toString().trim();

    clientThread = new WebServiceClient(SelectOptionActivity.this);
    clientThread.execute("teacher/" + teacherIdString);     

    try 
    {
        String xml = clientThread.get();

        DocumentBuilderFactory factory1 = DocumentBuilderFactory.newInstance();
        factory1.setNamespaceAware(true);
        try
        {
            DocumentBuilder builder = factory1.newDocumentBuilder();
            Document doc =builder.parse(new InputSource(new StringReader(xml))); 
            Element root = doc.getDocumentElement();
            if (doc != null) 
            {
                    NodeList nl = doc.getElementsByTagName("empId");
                    if (nl.getLength() > 0)
                    {
                        Node node = nl.item(0);
                        responseTeacherId = node.getTextContent();
                    }
                    NodeList n2=doc.getElementsByTagName("empName");
                    if (n2.getLength() > 0)
                    {
                        Node node = n2.item(0);
                        responseTeacherName = node.getTextContent();

                    }
            }

             Toast.makeText(getBaseContext(),""+responseTeacherId,10).show();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

Now getting error like

05-08 12:10:10.834: D/AndroidRuntime(524): Shutting down VM
05-08 12:10:10.834: W/dalvikvm(524): threadid=1: thread exiting with uncaught exception (group=0x40014760)
05-08 12:10:10.872: E/AndroidRuntime(524): FATAL EXCEPTION: main
05-08 12:10:10.872: E/AndroidRuntime(524): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.GDAProj/com.GDAProj.SelectOptionActivity}: java.lang.NullPointerException
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1739)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.ActivityThread.access$500(ActivityThread.java:122)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.os.Looper.loop(Looper.java:132)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.ActivityThread.main(ActivityThread.java:4123)
05-08 12:10:10.872: E/AndroidRuntime(524):  at java.lang.reflect.Method.invokeNative(Native Method)
05-08 12:10:10.872: E/AndroidRuntime(524):  at java.lang.reflect.Method.invoke(Method.java:491)
05-08 12:10:10.872: E/AndroidRuntime(524):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
05-08 12:10:10.872: E/AndroidRuntime(524):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
05-08 12:10:10.872: E/AndroidRuntime(524):  at dalvik.system.NativeStart.main(Native Method)
05-08 12:10:10.872: E/AndroidRuntime(524): Caused by: java.lang.NullPointerException
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:132)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:65)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:120)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.AlertDialog.<init>(AlertDialog.java:80)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.ProgressDialog.<init>(ProgressDialog.java:76)
05-08 12:10:10.872: E/AndroidRuntime(524):  at com.GDAProj.WebServiceClient.<init>(WebServiceClient.java:20)
05-08 12:10:10.872: E/AndroidRuntime(524):  at com.GDAProj.SelectOptionActivity.<init>(SelectOptionActivity.java:70)
05-08 12:10:10.872: E/AndroidRuntime(524):  at java.lang.Class.newInstanceImpl(Native Method)
05-08 12:10:10.872: E/AndroidRuntime(524):  at java.lang.Class.newInstance(Class.java:1301)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.Instrumentation.newActivity(Instrumentation.java:1022)
05-08 12:10:10.872: E/AndroidRuntime(524):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1730)
05-08 12:10:10.872: E/AndroidRuntime(524):  ... 11 more
Algolagnia answered 8/5, 2012 at 6:18 Comment(0)
A
11

Pass context of your current activity to AsyncTask class and using that context show progress dialog in onPreExecute() and dismiss it onPostExecute()

public  class WebServiceClient extends AsyncTask<String, Void, String>
{
 private static final String base_path = "http://www.gdaschools.in";
 protected static final String SLASH = "/";
 private ProgressDialog dialog;
 private Activity activity;

public WebServiceClient(Activity activity) {
    this.activity = activity;
    this.dialog = new ProgressDialog(activity);
}

@Override
 protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

@Override
    protected void onPostExecute(final Boolean success) {
        if (this.dialog.isShowing()) {
           this.dialog.dismiss();
        }

.
.
.

Code is only for your understanding..

Areta answered 8/5, 2012 at 6:26 Comment(11)
Sir, I want to call this from various activity. So is it the right way to call like WebServiceClient clientThread = new WebServiceClient(SelectOptionActivity.this); because i m getting error againAlgolagnia
@Areta this.dialog = new ProgressDialog(activity);Algolagnia
@Areta someone hinted that i m creating webserviceclient class's object before oncreate() that fired an error. SO i changed it and declared in each method. It worked now. But the problem is i m seeeing the progress dialog after the calculations are done not meanwhileAlgolagnia
If your activity reference is not present at the time of creation of webserviceclient class then you will get NUllPointerException in your case.. Not to declare in each method just declare once and after creation of your Activity not before.Areta
If you found this answer as helpful and solved your problem then you can accept it as a correct answer. So it will help you and other user also.Areta
@Areta its working but its still appearing after the processing is finished while it should appear while processing is being doneAlgolagnia
Are you sure You have initialized on one AsyncTask? If yes then put debug point in onPostExecute() to see process flow, whether it comes in that method.. (I have doubt it will not come at onPost())Areta
@Areta i m going to a different class from doInBackgrn() as u can c. can that be making the progressdialog invisible till it comes back from that class???Algolagnia
Nothing to do with different class, your progress dialog's lifecycle appears only for your AsyncTAsk class, onPre() it will created and in onPost() it will dismissed after completed doInBackground() else not.. So just check its really doInBack() is completed?Areta
let us continue this discussion in chatAlgolagnia
@Areta can u come in chat plz.Algolagnia
A
2

The instance of Activity is null because you are creating object of WebServiceClient before oncreate function. While passing Activity or Context be sure that Activity have created other wise it null will be passed and you will get this error

Ackerman answered 8/5, 2012 at 7:16 Comment(1)
thanks buddy. was really helpful. sadly i had only one acceptance power.Algolagnia

© 2022 - 2024 — McMap. All rights reserved.