2015-11-01 64 views
2

此代碼用於嘗試註冊數據庫的android studio應用程序。我的代碼在最後我的getBaseContext()代碼中不斷給我提供錯誤,我不知道爲什麼會如我所想它看起來確定!代碼是爲了一個實驗室,所以它應該是正確的,但我一直在犯錯誤!解析數據的getBaseContext()錯誤

有人可以告訴我嗎?任何幫助將非常感激!謝謝

public class AttemptRegistration extends 
    AsyncTask<String, Integer, String> { 

int success; 
String message = " "; 

@Override 
protected String doInBackground(String... args) { 
    try { 
     Map<String, String> params = new HashMap<String, String>(); 
     params.put("tag", "register"); 
     params.put("username", args[0]); 
     params.put("password", args[1]); 
     params.put("email", args[2]); 

     // 
     HttpUtility.sendPostRequest(params); 

     // 


     String response = HttpUtility.readRespone(); 

     JSONObject jObj = null; 

     try { 

      jObj = new JSONObject(response); 

      success = jObj.getInt("success"); 
      message = jObj.getString("message"); 


     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data" + e.toString()); 
     } 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 

     HttpUtility.disconnect(); 
     return message; 

} 
    protected void onPostExecute(String status) { 

    if (status !=null) { 

     Toast.makeText(getBaseContext(), status, Toast.LENGTH_LONG).show(); 

     if(success == 1) { 
      startActivity (new Intent(getBaseContext(), LoginActivity.class)); 
     } 
    } 

}

+0

郵棧跟蹤 –

+0

'getBaseContext()'不可用於'AsyncTask'的方法。如果您需要顯示Toast,則需要將參考傳遞給您的活動。如果你的AsyncTask是一個內部類,你可以調用'YourActivity.this.getBaseContext()' –

回答

1

。我的代碼一直給我下我getBaseContext()代碼中的錯誤在 結束,我不知道爲什麼,因爲我認爲它看起來不錯!

getBaseContext()ContextWrapper的方法。由於您收到cannot resolve the method錯誤,這意味着您的AsyncTask類未被定義爲繼承自ContextWrapperActivity E.g)的類的內部類。您可以將它Context傳遞到AsyncTask

public class AttemptRegistration extends AsyncTask<String, Integer, String> { 
    private final Context mContext; 
    public AttemptRegistration(Context context) { 
     mContext = context; 
    } 

,然後使用mContext代替getBaseContext()