2015-11-01 57 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()