2012-04-25 31 views
0

嗨我有這個帖子的方法在每一個活動。我怎麼能把這個帖子放到一個類中,如果錯誤我會知道?否則,我會將該錯誤消息解析爲json。Android post方法在一個類

private boolean login(String username, String password) { 
    TextView err = (TextView) findViewById(R.id.err); 
    boolean status = false; 
    String postData = "{\"Password\":\"" + password + "\",\"UserName\":\"" + username + "\"}"; 
    try { 
     String domain = getString(R.string.domain); 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpResponse response; 
     HttpPost httppost = new HttpPost(domain + "login"); 
     StringEntity se = new StringEntity(postData.toString(), "utf-8"); 
     se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
     httppost.setEntity(se); 
     httppost.setHeader("Accept", "application/json"); 
     httppost.setHeader("Content-type", "application/json"); 
     response = httpclient.execute(httppost); 
     if (response != null) { 
      HttpEntity r_entity = response.getEntity(); 
      String json = EntityUtils.toString(r_entity); 
      JSONObject jsonobj = new JSONObject(json); 
      status = jsonobj.getBoolean("result"); 
     } 


    } catch (Exception e) { 
     err.setText(e.getLocalizedMessage()); 
    } 
+1

我不知道你在問什麼 - 無論是把它放在一個超級類,或創建一個實用程序類具有該方法? – 2012-04-25 19:16:52

回答

0

製作一個util類。並使此方法成爲靜態的

public static boolean login(String username, String password,TextView err){} 

如果需要,還可以將它傳遞給上下文。然後將此方法稱爲您需要的地方

util.login(username, password,errorTextView); 
+0

所以如果我通過我的文本查看錯誤消息將顯示在我的活動?它會返回錯誤嗎? – user2514963 2012-04-26 09:36:13

+0

如果您在後臺線程中使用此方法,則不能使用textview.you只更新uithread上的textview。使用AsyncTask並在後期執行返回一個字符串並更新你的textview。 – 2012-04-26 09:46:50

0

如果可以同步執行並返回狀態。但是,你的問題似乎是如何異步獲取狀態。在這種情況下,可能會:

  1. 創建具有像receivedPostStatus(布爾值)
  2. 通的東西,實現了接口(或從基類的子類)插入的方法的接口(或基類)一個子類的AsyncTask它執行HTTP POST在其doInBackground()
  3. 然後在AsyncTask.onPostExecute,調用myImplementer.receivedPostStatus(狀態)