2016-10-18 140 views
-1

这里是我的代码: -从Android中的doInBackground()获取响应之前调用AsyncTask onPostExecute()?

Goals.java类

public class Goals extends AppCompatActivity{ 

    private ArrayList<Goal> result; 
    private RecyclerView.Adapter adapter; 
    private RecyclerView recyclerView; 
    private RecyclerView.LayoutManager layoutManager; 
    private ArrayList<Goal> dataFromServer; 
    private Toolbar toolbar; 


    //This is for back button 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
      case android.R.id.home: 
       startActivity(new Intent(this, MainActivity.class)); 
       finish(); 
       return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 


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

     recyclerView=(RecyclerView) findViewById(R.id.goal_recycler_view); 
     toolbar=(Toolbar) findViewById(R.id.toolbar); 


     recyclerView.setHasFixedSize(true); 

     layoutManager=new LinearLayoutManager(this); 
     recyclerView.setLayoutManager(layoutManager); 

     setSupportActionBar(toolbar); 

     //FOr back button 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     getSupportActionBar().setDisplayShowHomeEnabled(true); 
     getSupportActionBar().setDisplayShowTitleEnabled(false); 


     //fetch goal list from server and also its related action 
     getData(); 

     //Send Data to GoalAdaptor 
     showData(); 

    } 

    private void showData() { 
     Log.i("Show Date","Enter"); 
     System.out.println("Result Array List"+result.toString()); 
     adapter=new goalAdaptor(this, result); 
     recyclerView.setAdapter(adapter); 
    } 

    private void getData() { 

     result=new ArrayList<>(); 

     DownloadPlansFromServer server= new DownloadPlansFromServer(); 
     server.execute(); 

    } 


    class DownloadPlansFromServer extends AsyncTask<Void,Void,Boolean> 
    { 

     private ProgressDialog progressDialog; 
     Boolean planActive=false; 

     protected void onPreExecute() { 
      // NOTE: You can call UI Element here. 

      //UI Element 
      progressDialog = new ProgressDialog(Goals.this); 

      progressDialog.setMessage("Downloading Plans Data.."); 
      progressDialog.show(); 
     } 


     @Override 
     protected Boolean doInBackground(Void... params) { 



      try { 

       Response.Listener listener=new Response.Listener<JSONObject>() 
       { 
        @Override 
        public void onResponse(JSONObject response) { 
         try { 

          System.out.println("Inside the response"); 
          // Parsing json object response 
          // response will be a json object 

          System.out.println("Output is "+response.toString()); 


          //Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show(); 

          planActive=response.getBoolean("success"); 



          if (planActive) 
          { 
           JSONArray plansArray=response.getJSONArray("response"); 

           //get Plans Details 
           for (int p=0;p<plansArray.length();p++) 
           { 
            JSONObject plan=plansArray.getJSONObject(p); 

            //get Goals Details 
            JSONObject planGoals=plan.getJSONObject("goal"); 

            Goal goal=new Goal(); 
            goal.setGoal_name("Goal Name:- "+planGoals.getString("goal_name")); 

            Log.i("Goal Name is",planGoals.getString("goal_name")); 

            JSONObject currentValue=planGoals.getJSONObject("current_value"); 
            JSONObject targetValue=planGoals.getJSONObject("target_value"); 

            //Get the values parameter 
            ArrayList<String> parameterList=getTheParameter(planGoals.getString("goal_id")); 

            if (parameterList.isEmpty()) 
            { 
             System.out.println("Problem WHile Processing the parameter "); 
            } 
            else 
            { 
             String goalDescription="Reduce the value from"; 

             StringBuilder currentStringBuilder=new StringBuilder(); 

             for (int k=0;k<parameterList.size();k++) 
             { 
              currentStringBuilder.append(currentValue.getString(parameterList.get(k))+"/"); 
             } 

             StringBuilder targetStringBuilder=new StringBuilder(); 

             for (int k=0;k<parameterList.size();k++) 
             { 
              targetStringBuilder.append(targetValue.getString(parameterList.get(k))+"/"); 

             } 

             goal.setGoal_description(goalDescription+currentStringBuilder.toString()+" to "+ targetStringBuilder.toString()); 
            } 

            //Add the result to the array 
            result.add(goal); 

           } 

          } 


         } 
         catch (JSONException k) 
         { 
          Log.i("On Response",k.getMessage()); 
          k.printStackTrace(); 
         } 

        } 
       }; 


       Response.ErrorListener errorListener=new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 

         // Handle Error 
         if (error instanceof TimeoutError || error instanceof NoConnectionError) { 
          error.printStackTrace(); 
          Toast.makeText(getApplicationContext(), " this Network Error", Toast.LENGTH_SHORT).show(); 
         } else if (error instanceof AuthFailureError) { 
          //TODO 
          error.printStackTrace(); 
          Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show(); 
         } else if (error instanceof ServerError) { 
          //TODO 
          error.printStackTrace(); 
          Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show(); 
         } else if (error instanceof NetworkError) { 
          //TODO 
          error.printStackTrace(); 
          Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show(); 
         } else if (error instanceof ParseError) { 
          //TODO 
          error.printStackTrace(); 
          Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show(); 
         } 
         else error.printStackTrace(); 
        } 
       }; 

       String plan_url=Constants.url+"plan"; 

       JsonObjectHeader customRequest=new JsonObjectHeader(plan_url,null, listener, errorListener); 
       RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); 
       requestQueue.add(customRequest); 

       System.out.println("After custom Request"); 

       planActive=true; 

      }catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 


      return planActive; 
     } 


     protected void onPostExecute(Boolean unused) { 
      // NOTE: You can call UI Element here. 

      // Close progress dialog 
      progressDialog.dismiss(); 

      if (unused) 
      { 
       Log.i("Get Plan","Yes"); 
       //showData(); 

      } 

      else 
       Toast.makeText(getApplicationContext(),"No Plans Found",Toast.LENGTH_LONG).show(); 

     } 


    } 

    private ArrayList<String> getTheParameter(String goal_id) { 

     ArrayList<String> arrayList=new ArrayList<>(); 

     if (goal_id.equals("bp")) 
     { 
      arrayList.add("systolic"); 
      arrayList.add("diastolic"); 

      return arrayList; 
     } 
     else 
     { 
      arrayList.add(null); 
      return arrayList; 
     } 



    } 


} 

的问题是: - 让来自服务器的响应之前,onPostExecute()函数中执行。所以我会得到空结果列表。

JsonObjectHeader类是从服务器获取数据的基本抽排类。

回答

1

没有必要使用异步任务,而你想通过任何第三方库进行网络通话。因为volly为网络通话创建了自己的线程。

0

如果您正在使用volley库,然后删除AsyncTask和编写代码的简单方法

try { 

      Response.Listener listener=new Response.Listener<JSONObject>() 
      { 
       @Override 
       public void onResponse(JSONObject response) { 
        try { 

         System.out.println("Inside the response"); 
         // Parsing json object response 
         // response will be a json object 

         System.out.println("Output is "+response.toString()); 


         //Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show(); 

         planActive=response.getBoolean("success"); 



         if (planActive) 
         { 
          JSONArray plansArray=response.getJSONArray("response"); 

          //get Plans Details 
          for (int p=0;p<plansArray.length();p++) 
          { 
           JSONObject plan=plansArray.getJSONObject(p); 

           //get Goals Details 
           JSONObject planGoals=plan.getJSONObject("goal"); 

           Goal goal=new Goal(); 
           goal.setGoal_name("Goal Name:- "+planGoals.getString("goal_name")); 

           Log.i("Goal Name is",planGoals.getString("goal_name")); 

           JSONObject currentValue=planGoals.getJSONObject("current_value"); 
           JSONObject targetValue=planGoals.getJSONObject("target_value"); 

           //Get the values parameter 
           ArrayList<String> parameterList=getTheParameter(planGoals.getString("goal_id")); 

           if (parameterList.isEmpty()) 
           { 
            System.out.println("Problem WHile Processing the parameter "); 
           } 
           else 
           { 
            String goalDescription="Reduce the value from"; 

            StringBuilder currentStringBuilder=new StringBuilder(); 

            for (int k=0;k<parameterList.size();k++) 
            { 
             currentStringBuilder.append(currentValue.getString(parameterList.get(k))+"/"); 
            } 

            StringBuilder targetStringBuilder=new StringBuilder(); 

            for (int k=0;k<parameterList.size();k++) 
            { 
             targetStringBuilder.append(targetValue.getString(parameterList.get(k))+"/"); 

            } 

            goal.setGoal_description(goalDescription+currentStringBuilder.toString()+" to "+ targetStringBuilder.toString()); 
           } 

           //Add the result to the array 
           result.add(goal); 

          } 

         } 


        } 
        catch (JSONException k) 
        { 
         Log.i("On Response",k.getMessage()); 
         k.printStackTrace(); 
        } 

       } 
      }; 


      Response.ErrorListener errorListener=new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 

        // Handle Error 
        if (error instanceof TimeoutError || error instanceof NoConnectionError) { 
         error.printStackTrace(); 
         Toast.makeText(getApplicationContext(), " this Network Error", Toast.LENGTH_SHORT).show(); 
        } else if (error instanceof AuthFailureError) { 
         //TODO 
         error.printStackTrace(); 
         Toast.makeText(getApplicationContext(), "User not authorized", Toast.LENGTH_SHORT).show(); 
        } else if (error instanceof ServerError) { 
         //TODO 
         error.printStackTrace(); 
         Toast.makeText(getApplicationContext(), "Server error", Toast.LENGTH_SHORT).show(); 
        } else if (error instanceof NetworkError) { 
         //TODO 
         error.printStackTrace(); 
         Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show(); 
        } else if (error instanceof ParseError) { 
         //TODO 
         error.printStackTrace(); 
         Toast.makeText(getApplicationContext(), "Error consuming request", Toast.LENGTH_SHORT).show(); 
        } 
        else error.printStackTrace(); 
       } 
      }; 

      String plan_url=Constants.url+"plan"; 

      JsonObjectHeader customRequest=new JsonObjectHeader(plan_url,null, listener, errorListener); 
      RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); 
      requestQueue.add(customRequest); 

因为volley你可以在onResponse响应所以加onPostExecute这里面

0

你的问题是你正在onBackground(Void...)中创建一个额外的线程。

您的代码看:

  1. 开始onPreExecute。
  2. 显示对话框。
  3. 从onExExcute返回。
  4. 开始背景。
  5. 由Volley请求创建的新线程(线程#2)
  6. 从onBackground返回。
  7. 开始onPostExecute。
  8. 关闭对话框。
  9. 从onPostExecute返回。
  10. 从线程#2返回。

您需要使用Volley系统的阻塞方法。 This answer解释它。

RequestFuture<JSONObject> future = RequestFuture.newFuture(); 
JsonObjectRequest request = new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, future, future) 
volleyRequestQueue.add(request); 

try { 
    JSONObject response = future.get(); 
} catch (InterruptedException e) { 
} catch (ExecutionException e) { 
} 
0

这不是你的postExecute它的前

getData(); 

完成后,您

showData(); 

执行。理想情况下,将您的showData代码移动到您的postExecute中,您将按预期得到您的结果。

0

删除AsyncTask。

将doInBackgroud中的所有代码移入正常函数中。

在onResponse()中调用showSata()。

0

我认为你应该阅读文章,在哪里是一个很好的解释你为什么不应该使用AsyncTask。我的建议是开始使用改造(用于和HTTP工作)+你不必解析JSON你自己的,你可以在你Response对象使用@SerializedName注释

这里是a tutorial演示了如何从服务器获取数据,并填写回收鉴于

这里是

Call<LoginResponse> call = retrofit.create(ComeAroundAPIInterface.class).signin(data); 
    call.enqueue(new Callback<LoginResponse>() { 
     @Override 
     public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) { 
      if (response.isSuccessful()) {    
       onLoginSuccess(); 
       sharedPreferences = getSharedPreferences(LOGIN_COOKIE, Context.MODE_PRIVATE); 
       SharedPreferences.Editor editor = sharedPreferences.edit(); 
       editor.putBoolean("LOGIN",true); 
       editor.commit(); 
       progressDialog.dismiss(); 
       Intent intent = new Intent(LoginActivity.this, MainActivity.class); 
       intent.putExtra("user", (LoginResponse)response.body()); 
       startActivity(intent); 
       finish(); 
      } else { 
       progressDialog.cancel(); 
       onLoginFailed(); 
       Converter<ResponseBody, APIError> converter = retrofit.responseBodyConverter(APIError.class, new Annotation[0]); 
       APIError error = new APIError(); 
       try {error = converter.convert(response.errorBody());} catch (IOException e) {} 
       Toast.makeText(getBaseContext(),error.message(),Toast.LENGTH_SHORT).show(); 
      } 
     } 
     @Override 
     public void onFailure(Call<LoginResponse> call, Throwable t) { 
      onLoginFailed(); 
      Log.e("Login", t.toString()); 
     } 
    }); 

我的签名代码,这里是我的@SerializedName注释Response类

public class LoginResponse implements Parcelable{ 
    @SerializedName("id") 
    private String id; 
    @SerializedName("username") 
    private String username; 
    @SerializedName("email") 
    private String email; 
    @SerializedName("name") 
    private String name; 
    @SerializedName("sirname") 
    private String sirname; 

    //getters 
相关问题