使用AsyncTAsk解析JSON并填充列表时显示进度对话框

时间:2014-06-26 05:29:43

标签: android android-asynctask progressdialog

我有两个AsyncTasks。在第一个中,Iam以JSON形式从服务器获取数据并将其转换为String。在第二个中,我将String解析为对象。

ALl会在用户单击AlertDialog中的按钮后发生这种情况。在发生这种情况时,我想展示ProgressDialog。但目前ALertDialog在点击按钮后解散,这很好。但是进度对话框没有显示。

这是我的代码: -

private void PostString(String postedString)
            {
                // TODO Auto-generated method stub

                String postUrl  = EndPoints.PostURL;
                try 
                {
                    String Response = new Post().execute(postUrl).get();
                    String getRequesturl= url
                    String items = new FetchItems().execute(getRequesturl).get();
                    ArrayList<HashMap<String, String>> updatedPostList = new GetList().execute(items).get();

}

private class Post extends AsyncTask<String, String, String>
    {




        @Override
        protected String doInBackground(String... params)
        {
            // TODO Auto-generated method stub

            HttpResponse response =null;
            String resultString = "";
            String myResponseBody = "" ;
            // Creating HTTP client
            HttpClient httpClient = new DefaultHttpClient();
            // Creating HTTP Post
            HttpPost request = new HttpPost(params[0]);

            List<NameValuePair> nameValuePair =nameValuePairs


            try 
            {
                request.setEntity(new UrlEncodedFormEntity(nameValuePair));
                response = httpClient.execute(request);
                if(response.getStatusLine().getStatusCode()== 200)
                {
                    HttpEntity entity = response.getEntity();
                    if (entity != null)
                    {

                        InputStream inputStream = entity.getContent();
                        myResponseBody = convertToString(inputStream);
                    }
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return myResponseBody;
        }


private class FetchItems extends AsyncTask<String, String, String> 
    {
        // TODO Auto-generated method stub

        @Override
        protected String doInBackground(String... params) 
        {
            // TODO Auto-generated method stub
            HttpResponse response =null;
            String resultString = "";
            String myResponseBody = "" ;
            // Creating HTTP client
            HttpClient httpClient = new DefaultHttpClient();
            // Creating HTTP Post
            HttpGet request = new HttpGet(params[0]);


            try 
            {
                response = httpClient.execute(request);
                if(response.getStatusLine().getStatusCode()== 200)
                {
                    HttpEntity entity = response.getEntity();
                    if (entity != null)
                    {

                        InputStream inputStream = entity.getContent();
                        myResponseBody = convertToString(inputStream);
                    }
                }
            }
            catch(Exception e)
            {
            }
            return myResponseBody;
        }





        @Override
        protected void onPostExecute(String result) 
        {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            if(pd!=null && pd.isShowing())
                pd.dismiss();
        }





        @Override
        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            super.onPreExecute();


        }


private class GetList extends AsyncTask<String, String, ArrayList<HashMap<String, String>>>
    {


        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(String... params)
        {
            // TODO Auto-generated method stub
            myCList.clear();
            try {
                JSONObject jsonResponse = new JSONObject(new String(params[0]));
                JSONArray mtUsers = jsonResponse.getJSONArray("ListOfC");
                for (int i = 0; i < mtUsers.length(); i++)
                {
                    JSONObject menuObject = mtUsers.getJSONObject(i);
//Parsing

                    map = new HashMap<String,String>();
                    map.put(My items here)

                    myCommentsList.add(map);

                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Collections.reverse(myList);
            return myList;
        }



    }



case R.id.btnAdd:
            scrollNews.fullScroll(v.FOCUS_DOWN);
            btnAddComms.setPressed(true);

            builder = new AlertDialog.Builder(NewsDetails.this);
            builder.setTitle("Post Comment");
            builder.setIcon(R.drawable.post_comment_button);


            final EditText input1 = new EditText(NewsDetails.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);

            input1.setLayoutParams(lp);
            builder.setView(input1);


            builder.setPositiveButton("Post", new DialogInterface.OnClickListener()
            {

                public void onClick(DialogInterface dialog, int id) 
                {

                    pd = new ProgressDialog(Details.this);
                    pd.setMessage("Posting..");
                    pd.show();
                    pd.setCancelable(true);

                    postedString= input1.getText().toString();
                    dialog.dismiss();

                    if(postedString.length()>0)
                    {
                        Post(postedString);

                    }
                    else
                    {
                        Toast.makeText(Details.this, "Please enter a text.", Toast.LENGTH_LONG).show();
                        input1.findFocus();
                    }





                }

1 个答案:

答案 0 :(得分:0)

创建ProgressDialog作为实例变量。

pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching data");

在AsyncTask的onPreExecute()方法中:

pDialog.show();

在AsnycTask的onPostExecute()方法中:

pDialog.dismiss();

注1:您不需要多个AsyncTasks,您可以单独在第一个AsyncTask中完成整个获取和解析,因为您在另一个之后调用一个AsyncTask。

String Response = new Post().execute(postUrl).get();
String getRequesturl= url;
String items = new FetchItems().execute(getRequesturl).get();
ArrayList<HashMap<String, String>> updatedPostList = new GetList().execute(items).get();

注意2:当您在UI线程上执行asyncTask.execute.get()时,您的UI将被阻止,这是不受鼓励的。因此,只需调用asyncTask.execute()并在后台发生所有事情时显示进度对话框。