2015-07-20 174 views
0

我正在調用我主要活動類中的Async類。當POST已執行時,我想將結果返回到主要活動。將上下文傳遞給異步類

public class MainActivity extends Activity implements OnClickListener, AsyncResponse{ 
    public Context context; 
    PostKey asyncTask = new PostKey(context); 

    public void onCreate(Bundle savedInstanceState) { 
     asyncTask.delegate = this; 
    } 

    public void onClick(View v) { 
     asyncTask.delegate = this; 
     new PostKey(context).execute(keyValue); 
    } 

    public void processFinish(String output){ 
     //this you will received result fired from async class of onPostExecute(result) method. 
     Log.d("Result", output); 
    } 
} 


public class PostKey extends AsyncTask<String, String, String> { 
    public AsyncResponse delegate = null; 
    public Context context; 

    public PostKey(Context context){ 
     this.context = context.getApplicationContext(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     return postData(params[0]); 
    } 

    @Override 
    protected void onPostExecute(String result){ 
     this.context = context.getApplicationContext(); 
     delegate = (AsyncResponse) context; 
    } 

    delegate.processFinish(result); 
} 

public interface AsyncResponse { 
    void processFinish(String output); 
} 

每當我嘗試運行應用程序,我立刻得到所引起的空指針異常的致命錯誤。該空指針指的是以下幾點:

public PostKey(Context context){ 
    this.context = context.getApplicationContext(); 
} 

& PostKey asyncTask = new PostKey(context);

在第二種情況下,我可以得到context是空的,但我要在這裏傳遞變量。

+0

在您的主要活動,'公共上下文的背景下;'聲明,但從未給予價值?它是空的..所以試圖調用PostKey構造函數,試圖調用null對象上的'getApplicationContext()'函數肯定會給你一個NullPointerException。 – Gosu

+0

可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-fix-it) – Gosu

+0

@Gosu在每個代碼片段中,我發現'context'變量是在async類中設置的。由於'私人PostKey(上下文上下文){}'我必須在主要活動中傳遞變量 – Orynuh

回答

0

你好Oryna你傳遞null上下文值作爲參數只是這個

new PostKey(context).execute(keyValue); 

new PostKey(MainActivity.this).execute(keyValue); 

更換這些線路和異步任務的構造替代代碼

public PostKey(Context context){ 
    this.context = context.getApplicationContext(); 
} 

public PostKey(Context context){ 
    this.context = context; 
} 
2

Activity已經是Context,所以你不要保留對它的引用。只需使用this。另一方面,活動必須經過其生命週期,然後才能使用上下文。刪除

public Context context; 
PostKey asyncTask = new PostKey(context); 

,並在您onCreate添加

PostKey asyncTask = new PostKey(this); 

。並請在您的onCreate

0

試加super.onCreate(savedInstanceState);的第一件事就是用this.context = getApplicationContext();代替