2010-07-20 61 views
1

我試圖做我認爲是一個相當簡單的任務來驗證我的服務器上的用戶。我使用AsyncTask作爲Activity的私有子類,但是當我嘗試在驗證後填充用戶對象時,它始終將其設置爲null。如何調用onPostExecute()方法導致這種情況有什麼奇怪的地方?我最初有AsyncTask作爲它自己的類,但遇到了同樣的問題,所以我嘗試使用私有子類來解決此問題。任何幫助?謝謝。從AsyncTask返回數據導致空指針錯誤

這裏是我的代碼:

public class Testing extends Activity { 

    private User user; 

    public User getUser() { 
     return this.user; 
    } 

    public void setUser(User value) { 
     this.user = value; 
    } 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     final ImageView iconImage = (ImageView) this.findViewById(R.id.image); 
     final Button testButton = (Button) this.findViewById(R.id.testButton); 
     final TextView text = (TextView) this.findViewById(R.id.text); 
     iconImage.setImageResource(R.drawable.logo_real); 
     testButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       LoginTask loginTask = (LoginTask) new LoginTask().execute(new Void[0]); 
       text.setText(user.getFormattedFullName()); 
      } 
     }); 
    } 

    private class LoginTask extends AsyncTask<Void, Void, User> { 

     public LoginTask() { 
     } 

     protected User doInBackground(Void... params) { 
      User newUser = new User(); 
      try { 
       System.out.println("testing task"); 
       HttpClient client = new DefaultHttpClient(); 
       HttpGet request = new HttpGet("http://10.0.2.2:8080/Dugout/[email protected]&PASSWORD=password"); 
       HttpResponse response = client.execute(request); 
       HttpEntity entity = response.getEntity(); 
       InputStream is = entity.getContent(); 
       String message = ""; 
       String inputLine = ""; 
       BufferedReader bf = new BufferedReader(new InputStreamReader(is)); 
       while ((inputLine = bf.readLine()) != null) message+=inputLine; 
       JSONObject returnedUser = new JSONObject(message); 
       int userId = returnedUser.getInt("userId"); 
       boolean loginSuccess = returnedUser.getBoolean("login_success"); 
       String firstName = returnedUser.getString("firstName"); 
       String lastName = returnedUser.getString("lastName"); 
       newUser.setId(userId); 
       newUser.setFirstName(firstName); 
       newUser.setLastName(lastName); 
       newUser.setLoginSuccess(loginSuccess); 
       return newUser; 
      } catch (Exception e) { 
       newUser.setLoginSuccess(false); 
       return newUser; 
      } 
     } 

     protected void onPostExecute(User user) { 
      setUser(user); 
     } 

    } 

} 

回答

2

應該

protected void onPostExecute(User user) { 
    text.setText(user.getFormattedFullName()); 
} 

您正在嘗試它已經被AsyncTask創建之前訪問user(整點是doInBackground(..)在後臺線程中運行,因此不會阻塞UI線程)。