gpt4 book ai didi

android - MainActivity 为空

转载 作者:行者123 更新时间:2023-11-29 00:24:22 25 4
gpt4 key购买 nike

我的 Android 项目有问题。我正在处理 fragment 。其中一个类是 MainActivity 类,它扩展了 FragmentActivity。还有两个扩展 fragment 的类。我想从 fragment 中调用 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方法的 fragment :

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());

我不知道为什么 MainActivitynull。希望有人能给我一个解决这个问题的建议。

最佳答案

正如其他人所指出的,您试图在将 Fragment 附加到 Activity 之前引用 Activity

然而,也就是说,您不应该尝试以您尝试的方式直接从 Fragment 调用 Activity 自己的方法。这是可以做到的,但对于使用 Fragments 进行设计来说,这是一种不好的做法。

Fragment 应该是模块化和可重用的 - 因此 Fragment 不需要知道 Activity 是什么类型托管它或可以调用哪些方法。

相反,您应该在 Fragment 本身中定义一个回调接口(interface),并让 Activity 实现该接口(interface)和相关方法。

参见 Event Callbacks Fragments 指南。

这样做意味着 Fragment 总是“知道”接口(interface)定义了哪些方法以及如何使用它们。只要使用 Fragment 的所有 Activities 实现了接口(interface),一切就应该可以正常工作。

关于android - MainActivity 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com