在 Button 的 OnClickListener 中呼叫 p2.save(this, new SaveListener()) 時,編譯錯誤:
The method save(Context, SaveListener) in the type BmobObject
is not applicable for the arguments
(new View.OnClickListener(){}, new SaveListener(){})
匿名內部類 new OnClickListener() 的 this 指向該 Listener 實例(型別 View.OnClickListener),而非 Activity(Context 子型別)。BmobObject.save() 第一個參數要求 Context。
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Person p2 = new Person();
p2.setName("lucky");
p2.setAddress("北京海澱");
// 關鍵修正:使用 HelloWorldActivity.this 或 getApplicationContext()
p2.save(HelloWorldActivity.this, new SaveListener() {
@Override
public void onSuccess() {
Toast.makeText(HelloWorldActivity.this,
"添加資料成功,objectId:" + p2.getObjectId(),
Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(int code, String msg) {
Toast.makeText(HelloWorldActivity.this,
"建立資料失敗:" + msg, Toast.LENGTH_LONG).show();
}
});
}
});
| 場合 | 寫法 | 說明 |
|---|---|---|
| Activity 內部類 | OuterActivity.this | 明確指向外層 Activity 實例 |
| 全域可用 | getApplicationContext() | Application 生命週期最長,避免記憶體洩漏 |
| View 持有 | view.getContext() | 任何 View 皆可取得其附屬 Context |
| Fragment 中 | requireContext() | API 23+,非 null 保證 |
WeakReference 或 Application Context匿名內部類的 this 指向該類別實例,非外層 Activity。在需要 Context 的 API(如 Bmob save、Toast、Dialog、Intent)中,務必使用 ActivityName.this、getApplicationContext() 或 view.getContext() 明確傳遞正確 Context。