我試圖從一個片段傳值的活動,我可以,因爲我得到也不例外之間傳遞數據。在我的片段中,我必須選擇一個在FrameLayout中呈現的星座。 要做活動和片段之間的通信我正在使用回調。安卓片段和活動
唯一的例外是:
java.lang.NullPointerException: Attempt to invoke interface method
'void
com.converter.android.dailyhoroscope.HoroscopeChoice$OnInfoChangedListener.onInfoChanged(java.lang.String)'
on a null object reference
at
com.converter.android.dailyhoroscope.HoroscopeChoice$1.onClick(HoroscopeChoice.java:133)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
在片段,我有以下代碼:
public class HoroscopeChoice extends DialogFragment {
public HoroscopeChoice() {
}
/******************************
* Callback
********/
public static void setOnInfoChangedListener(OnInfoChangedListener callback) {
mCallback = callback;
}
public interface OnInfoChangedListener {
public void onInfoChanged(String horosocopo);
}
(...)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_horoscope_choice,
container, false);
Button aquarius;
aquarius = (Button) view.findViewById(R.id.aquarius1);
final int id = view.getId();
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String horoscopo = onClick2(v.getId());
mCallback.onInfoChanged(horoscopo);
}
};
aquarius.setOnClickListener(onClickListener);
return view;
}
public String onClick2(int id)
{
String horoscopo="";
if (id == R.id.aquarius1) {
horoscopo = "Aquarius";
}
(...)
return horoscope;
}
上的活動,如果我試圖把setOnInfoChangedListener(this);
要解決的例外,我有,我收到另一個錯誤「無法解析方法setOnInfoChangedListener」。
活動:
public class SchedulerActivity extends Activity implements HoroscopeChoice.OnInfoChangedListener {
(...)
setOnInfoChangedListener(this);
public void onInfoChanged(String horoscopo) {
String sign="";
mHoroscopeDisplay = (TextView) findViewById(R.id.dailyHoroscope4);
mHoroscopeDisplay.setText(horoscopo);
saveData(dHosocope, sign);
}
}
你能幫助我嗎?
我在這裏有一個答案給你http://stackoverflow.com/questions/14247954/communicating-between-a-fragment-and-an-activity-best-practices/25392549#25392549 – Eenvincible