0

I’m using ksoap to call a web service. When Application starts or when i scroll to end of page Application fetches data from Web Service correctly and it shows data as well as i want, But When I want to show Progress Dialog in a AsyncTask it doesn’t work correctly. It shows Progress Dialog after PostExecute in a blik of eyes. So, What's wrong in my code ? I can't understand where is my problem. ;-)

I have a web service class called ElvatraWebService:

Here is a Method witch is fetch latest post with Asynctasks

private  String GetLastPublicPosts(int counter){
    ...
    ...
    ...
    ...
    return resTxt; //Returns JSON String 
}



public String getLatestPost(int counter, Activity a){

    CallLatestPost task = new CallLatestPost(counter,a);
    try {
        strJSON = task.execute("getLatest").get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //Log.i("sss", "--" + strJSON);
    return strJSON;

}

private class CallLatestPost extends AsyncTask<String, Void, String> {
    private int Counter = 0;
    private ProgressDialog dialog;
    private Activity activity;
    private Context context;


    public CallLatestPost (int c,Activity actt) {
        super();
        this.Counter = c;
        activity = actt;
        context = actt;
        dialog = new ProgressDialog(this.context);

    }

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

        ElvatraWebService elws = new ElvatraWebService();
        String tmp = elws.GetLastPublicPosts(this.Counter);
        //Log.i("strJSON",strJSON);
        return tmp;
    }

    @Override
    protected void onPostExecute(String result) {
        //Set response 
        super.onPostExecute(result);

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

    }

    @Override
    protected void onPreExecute() {

        super.onPreExecute();



        dialog = new ProgressDialog(context);
        dialog.setMessage("Connecting...");
        //dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.show();

        Log.i("@@@Async", "=== " + "PreExec");
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }

}

I have a Class called post. It will call getLatestPost from Elvatrawebservice. Then it will convert JSON String to JsonArray with PostAdapter class. PostAdapter is a class extends BaseAdapter.

In Main Activity I call a local Method called LoadContent in onCreate method. Here is MainActivity Class

 public class MainActivity extends Activity {


String displayText="";
public TextView tv;
public ListView lv;
public ProgressBar pg;


int theCounter=20;
String[] strTAG = new String[] {"title","photo","date","desc","linkurl"};
//int[] intField = new int[] {R.id.title,R.id.imgPost, R.id.Date, R.id.desc, R.id.link};
ListAdapter sa;
List<HashMap<String,Object>> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recentposts);


    lv = (ListView) findViewById(R.id.list);    
    lv.setOnScrollListener(new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {

           final int lastItem = firstVisibleItem + visibleItemCount;
           if(lastItem == totalItemCount) {
               //load more data
            // Load content of listview
            LoadContent();


           }
        }
    });




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}



@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass

    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}



public void LoadContent(){

    lv = (ListView) findViewById(R.id.list);

    Post p = new Post(theCounter);
    theCounter+=20;
    if (p.GetLatestPosts(lv,MainActivity.this))
    {
        //tv.setText("true");

    }   

}   

}
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
M. Javad Mohebbi
  • 415
  • 1
  • 3
  • 14

1 Answers1

1

You have

 task.execute("getLatest").get();

You should not call get() as this blocks the ui thread waiting for the result making it asynctask asynchronous no more. Just use

 task.execute("getLatest");

You can return result in doInBackground and update ui in onPostExecute.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • When i change this line `strJSON = task.execute("getLatest").get()` to `strJSON = task.execute("getLatest")`, I will have Type Mismatch Error. and it will suggested me to change `strJson` type from `String` to `AsyncTask`. So, What should i do ? – M. Javad Mohebbi May 02 '14 at 09:49
  • There in no need for `strJSON = task.execute("getLatest")` just `task.execute("getLatest")` . you can use a interface as a call back to the activity – Raghunandan May 02 '14 at 11:20
  • @user3594119 check this http://stackoverflow.com/questions/16752073/how-do-i-return-a-boolean-from-asynctask use only `task.execute("getLatest")` you can result back in activity using a interface – Raghunandan May 02 '14 at 11:21