Instanz von DBHelper erzeugen (NullpointerException wegen fehlendem Context[mydb=null]) [ERLEDIGT]

  • 3 Antworten
  • Letztes Antwortdatum
Rastaman

Rastaman

Stamm-User
148
Hallo,

Wie erzeuge Ich in meinem Fragment eine Instanz von meiner DBHelper Klasse?

Code:
public class AddDataFragment extends Fragment {
    DbHelper mydb;
    [...]


    mydb = new DbHelper(getActivity());

Ich habe bereits alles an Anforderungen probiert... (this), (getActivity()), (getContext()).
Kann mir jemand sagen ob Ich einen Denkfehler mache?

MfG
Rastaman
 
Seltsam, normalerweise sollte es mit getActivity() funktionieren. Hast du getApplicationContext() einmal ausprobiert?
 
Ich hab es mit
Code:
        Context context = getContext();
        mydb = new DbHelper(context);

gelöst. Aber wieso es vorher nicht ging weiß Ich nicht...
 
du hättest deine db initialisierung in onAttach() machen sollen damit getActivity() dir auch wirklich eine Activity zurückgeben kann.
onAttach() wird nämlich dann aufgerufen sobald das fragment an die Activity angehangen wurde...ab diesem Moment liefert dir getActivity() erst die Activity...

getBaseContext() ist besser. So läufst du nciht gefahr einen falschen Context zu bekommen.

edit:
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.

Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().

von SO
 
Zuletzt bearbeitet:
Zurück
Oben Unten