从onPostExecute内部AsyncTask获取结果到OnCreate

时间:2015-04-17 11:14:29

标签: java android android-asynctask

我正在使用内部AsyncTask来计算远程数据库的平均值, 我得到的结果却是

问题是:仅在“onPostExecute”中可用的平均值,我希望在“On Create()”中可以访问此值,因此我可以将其发送到另一个AsyncTask中活性

public class Place_details extends Activity {
    RatingBar PlaceRatingBar;
    UserSessionManager session;
    String ID;

    Double [] Place_rates;
    int Total_place_rates;
    float Average_place_rates;

    // JSON
    JSONParser jsonparser;
    JSONObject JSONObject;
    ProgressDialog ProgressDialog;
    JSONArray jsonArray1;
    int value;


    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_place_details);    

         PlaceRatingBar = (RatingBar) findViewById (R.id.Place_rating);

         jsonparser = new JSONParser();

        //Session
        session = new UserSessionManager(Place_details.this);

        new getPlaceRating().execute() ;

     // Here I get 0.0 and not the correct Average 
        Toast.makeText(Place_details.this, ""+Average_place_rates, Toast.LENGTH_SHORT).show();


    } // End Of OnCreate    


    public class getPlaceRating extends AsyncTask<String,String,String>{ 

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                ProgressDialog = new ProgressDialog(Place_details.this);
                ProgressDialog.setTitle("Wait....");
                ProgressDialog.setIndeterminate(false);
                ProgressDialog.setCancelable(true);
                ProgressDialog.show();
            }


            @Override
            protected String doInBackground(String...parma) {
                // TODO Auto-generated method stub
                List<NameValuePair> list = new ArrayList<NameValuePair>();

                // passing place_id value
                list.add(new BasicNameValuePair("id",String_Place_id));
                try {
                JSONObject = jsonparser.makeHttpRequest("http://192.168.1.2/Yourguideapplication/Place_rating2.php", "POST", list);
                Log.e("pass 1", "connection success ");
                }
                catch (Exception e) {
                    Log.e("Fail 1", "Fail connection");
                }

                try {
                value = JSONObject.getInt("value");
                if (value==1){
                    //Place Rating
                    jsonArray1 = JSONObject.getJSONArray("Place_rating");
                    Place_rates = new Double[jsonArray1.length()];
                    Total_place_rates =0;
                    for (int i = 0 ; i < jsonArray1.length() ; i++)
                    {
                        JSONObject object = jsonArray1.getJSONObject(i);
                        Place_rates[i] = object.getDouble("Rating_box");
                        Total_place_rates+= Place_rates[i];
                    }               
                } else {
                    value = 0;

                }
                } catch (Exception e){
                    Log.d("ERORR",e.getMessage());
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                if (value == 1){
                    //Place Rating
                    Average_place_rates = (float) (Total_place_rates/jsonArray1.length());
                    PlaceRatingBar.setRating((float) Average_place_rates);
                } else {
                    Toast.makeText(Place_details.this, "Error", Toast.LENGTH_LONG).show();      
            }
                ProgressDialog.dismiss();
            }
        }

}

谢谢

1 个答案:

答案 0 :(得分:3)

您可以创建类似

的内容
private interface CallbackListener<T> {
     void onComputingFinished(T arg);
}

让您的活动实现此界面。

public class Place_details extends Activity implements CallbackListener<String> {
  @Override
  public void onComputingFinished(String arg) {
     //do your stuff here
  }

在AsynTask类中将其注册为侦听器(在AsyncTask类中创建字段和构造函数):

public class GetPlaceRating extends AsyncTask<String,String,String>{     
    private CallbackListener<String> mListener;
    public GetPlaceRating(CallbackListener<String> listener) {
         mListener = listener;
    }

启动任务时

new GetPlaceRating(this).execute() ;

并在onPostExecute中调用

if (mListener != null) mListener.onComputingFinished(*your arg*);

在本例中我使用String替换泛型T,希望你明白你可以使用你想要的任何东西。

<强>编辑: 如果参数类型相同,则可以将接口的签名更改为:

private interface CallbackListener<T> {
   void onComputingFinished(T ...args);
}

并将它们作为数组访问:args [0],args [1]。 或者只指定要传递的具体参数,例如String,int和SomeClass:

private interface CallbackListener {
   void onComputingFinished(String str, int value, SomeClass obj);
}