我的Android项目有问题。我正在处理碎片。其中一个类是MainActivity
类,它扩展了FragmentActivity
。还有两个扩展片段的类。我想从片段中调用MainActivity
方法,但每次它都给我一个NullPointerException
。我已经尝试了一切,但问题仍然存在。
MainActivity
看起来像这样:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mySectionsPagerAdapter;
ViewPager myViewPager;
ActionBar myactionBar;
Schuldet_mir fr_schuldetMir;
Ich_schulde fr_ichSchulde;
public DataBaseHandler myDBHandler;
public String testString = null;
// ------------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myactionBar = getActionBar();
myactionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
setSectionsPagerAdapter();
initActionbar();
initFragments();
}
// ------------------------------------------------------------------------
@Override
protected void onResume() {
super.onResume();
openDB();
populateListViewFromDB();
}
// ------------------------------------------------------------------------
private void setSectionsPagerAdapter() {
mySectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
myViewPager = (ViewPager) findViewById(R.id.pager);
myViewPager.setAdapter(mySectionsPagerAdapter);
myViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
myactionBar.setSelectedNavigationItem(position);
}
});
}
// ------------------------------------------------------------------------
private void initActionbar() {
for (int i = 0; i < mySectionsPagerAdapter.getCount(); i++) {
myactionBar.addTab(myactionBar.newTab()
.setText(mySectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
// ------------------------------------------------------------------------
private void initFragments() {
fr_schuldetMir = (Schuldet_mir)mySectionsPagerAdapter.getItem(0);
fr_ichSchulde = (Ich_schulde)mySectionsPagerAdapter.getItem(1);
}
// ------------------------------------------------------------------------
private void openDB() {
myDBHandler = new DataBaseHandler(this);
myDBHandler.open();
}
private void closeDB() {
myDBHandler.close();
}
public String test() {
testString = "Test Test TEst!";
return testString;
}
// ------------------------------------------------------------------------
private void populateListViewFromDB() {
fr_schuldetMir.populateListViewFromDB();
}
// ------------------------------------------------------------------------
@Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
片段,调用MainActivity
的方法:
public class Schuldet_mir extends Fragment {
public static String ARG_SECTION_NUMBER = "section_number";
ListView listView;
TextView verliehenesGeld;
float _betrag = 0;
float gesamt = 0;
int iconID;
EditText eintrag_name, eintrag_betrag, eintrag_grund;
String name = "";
String grund = "";
String datum = "";
MainActivity mainActivity = (MainActivity)getActivity();
GetDate date;
public Cursor cursor;
public Schuldet_mir(int position) {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_schuldet_mir, container, false);
listView = (ListView)v.findViewById(R.id.listView1);
verliehenesGeld = (TextView)v.findViewById(R.id.textView1);
verliehenesGeld.setText(null);
return v;
}
// --------------------------------------------------------------------
public void btnClick_SchulderEintragen(View v) { //Button Klick to Add Schuldner
openDialog();
}
// --------------------------------------------------------------------
private void openDialog() { //Dialog erstellen
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog1);
dialog.setTitle("Schulden Hinzufügen");
dialog.setCancelable(false);
eintrag_name = (EditText)dialog.findViewById(R.id.editText_name);
eintrag_betrag = (EditText)dialog.findViewById(R.id.editText_betrag);
eintrag_grund = (EditText)dialog.findViewById(R.id.editText_grund);
Button hinzufügen = (Button)dialog.findViewById(R.id.button2);
Button abbrechen = (Button)dialog.findViewById(R.id.button1);
hinzufügen.setOnClickListener(new OnClickListener() { //Buttonklick Hinzufügen
@Override
public void onClick(View v) {
name = eintrag_name.getText().toString();
_betrag = Float.valueOf(eintrag_betrag.getText().toString());
grund = eintrag_grund.getText().toString();
datum = date.returnDate();
iconID = R.drawable.user_image3;
mainActivity.myDBHandler.insertRow(name, _betrag, grund, datum);
populateListViewFromDB();
dialog.dismiss();
}
});
// --------------------------------------------------------------------
abbrechen.setOnClickListener(new OnClickListener() { //Buttonklick Abbrechen
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
// --------------------------------------------------------------------
@SuppressWarnings("deprecation")
public void populateListViewFromDB() { //ListView mit Werten aus der db befüllen
// cursor = mainActivity.myDBHandler.getAllRows();
if(mainActivity == null) {
Log.e("***TEST***", "MAIN ist NULL");
}
mainActivity.startManagingCursor(cursor = mainActivity.myDBHandler.getAllRows());
String[] dbSpaltenNamen = new String[] {DataBaseHandler.KEY_NAME, //die spalteneinträge wie
DataBaseHandler.KEY_BETRAG, //angeordnet in die jeweiligen
// DataBaseHandler.KEY_GRUND, //id's des custom listzeile zuordnen
DataBaseHandler.KEY_DATUM};
int[] zuListViewIDs = new int[] {R.id.txt_name, //hier die id's. name zu name
R.id.txt_betrag, //betrag zu betrag...
R.id.datum};
SimpleCursorAdapter myCursorAdapter
= new SimpleCursorAdapter
(getActivity(), R.layout.list_zeile, cursor, dbSpaltenNamen, zuListViewIDs);
listView.setAdapter(myCursorAdapter);
}
private float gesamtSchulden(EditText betrag) {
gesamt += Float.valueOf(betrag.getText().toString());
return gesamt;
}
// --------------------------------------------------------------------
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mainActivity = (MainActivity) activity;
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " Fehler: Keine MainActivity-Instanz!");
}
}
}
SectionsPagerAdapter
:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Schuldet_mir f1;
private Ich_schulde f2;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
//damit nicht immer wieder bei einer Anzeige ein neues fragment instanziiert wird,
//wurde diese Methode angepasst. D.h. es werden die vorher erzeugten framgente verwendet
if(position == 0) {
if (f1 == null) {
f1 = new Schuldet_mir(position);
}
return f1;
}
else {
if (f2 == null) {
f2 = new Ich_schulde(position);
}
return f2;
}
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "... schuldet mir";
case 1:
return "Ich schulde ...";
}
return null;
}
}
NullPointerException
:
12-29 11:30:30.172: D/ActivityThread(26852): setTargetHeapUtilization:0.25
12-29 11:30:30.172: D/ActivityThread(26852): setTargetHeapIdealFree:8388608
12-29 11:30:30.172: D/ActivityThread(26852): setTargetHeapConcurrentStart:2097152
12-29 11:30:30.192: V/ActivityThread(26852): Class path: /data/app/debtmanager.mainfolder-2.apk, JNI path: /data/data/debtmanager.mainfolder/lib
12-29 11:30:30.262: E/***TEST***(26852): MAIN ist NULL
12-29 11:30:30.272: D/AndroidRuntime(26852): Shutting down VM
12-29 11:30:30.272: W/dalvikvm(26852): threadid=1: thread exiting with uncaught exception (group=0x410fb2a0)
12-29 11:30:30.272: E/AndroidRuntime(26852): FATAL EXCEPTION: main
12-29 11:30:30.272: E/AndroidRuntime(26852): java.lang.RuntimeException: Unable to resume activity {debtmanager.mainfolder/debtmanager.mainfolder.MainActivity}: java.lang.NullPointerException
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2608)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2636)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2103)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.ActivityThread.access$600(ActivityThread.java:138)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1204)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.os.Handler.dispatchMessage(Handler.java:99)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.os.Looper.loop(Looper.java:137)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.ActivityThread.main(ActivityThread.java:4872)
12-29 11:30:30.272: E/AndroidRuntime(26852): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 11:30:30.272: E/AndroidRuntime(26852): at java.lang.reflect.Method.invoke(Method.java:511)
12-29 11:30:30.272: E/AndroidRuntime(26852): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-29 11:30:30.272: E/AndroidRuntime(26852): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
12-29 11:30:30.272: E/AndroidRuntime(26852): at dalvik.system.NativeStart.main(Native Method)
12-29 11:30:30.272: E/AndroidRuntime(26852): Caused by: java.lang.NullPointerException
12-29 11:30:30.272: E/AndroidRuntime(26852): at fragments.Schuldet_mir.populateListViewFromDB(Schuldet_mir.java:114)
12-29 11:30:30.272: E/AndroidRuntime(26852): at debtmanager.mainfolder.MainActivity.populateListViewFromDB(MainActivity.java:105)
12-29 11:30:30.272: E/AndroidRuntime(26852): at debtmanager.mainfolder.MainActivity.onResume(MainActivity.java:49)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1187)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.Activity.performResume(Activity.java:5265)
12-29 11:30:30.272: E/AndroidRuntime(26852): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2598)
12-29 11:30:30.272: E/AndroidRuntime(26852): ... 12 more
在第114行跟随代码。
mainActivity.startManagingCursor(cursor = mainActivity.myDBHandler.getAllRows());
我不知道为什么MainActivity
是null
。希望有人可以给我一个解决这个问题的建议。
答案 0 :(得分:2)
正如其他人所指出的那样,您试图在Activity
附加到Fragment
之前引用Activity
。
但是,您不应该尝试直接从Activity's
调用Fragment
自己的方法,就像您尝试这样做一样。可以这样做,但使用Fragments
进行设计是不好的做法。
Fragment
是模块化和可重复使用的 - 因此Fragment
不应该知道托管它的Activity
是什么类型,或者可能是什么方法可以打电话。
相反,您应该在Fragment
本身中定义一个回调接口,让Activity
实现该接口和相关方法。
请参阅Fragments
的{{3}}指南。
这样做意味着Fragment
始终知道&#39;接口定义了哪些方法以及如何使用它们。只要使用Activities
实现接口的所有Fragment
都可以正常工作。
答案 1 :(得分:0)
MainActivity mainActivity = (MainActivity)getActivity();
这是问题
将其替换为
MainActivity mainActivity;
因为你已经
了@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mainActivity = (MainActivity) activity;
}
您可以简单地使用getActivity()
而不是返回此片段与
答案 2 :(得分:0)
移动 -
setSectionsPagerAdapter();
initFragments();
从onCreate()
致电onResume()
方法。
答案 3 :(得分:0)
问题是由这一行引起的:
MainActivity mainActivity = (MainActivity)getActivity(); // in Schuldet_mir
这在片段的构造函数中调用。 Fragment.getActivity()
构建完成后必须调用Fragment
。您应该在使用getActivity()
字段的所有地方调用mainActivity
。此外,您应该将populateListViewFromDB()
从活动的onResume()
方法移动到片段的onResume()
方法。
你还有一个错误。你的片段必须有一个空的构造函数。您应该查看this问题的答案。