Error
Error

Reputation: 830

Call method in Fragment from Activity return java.lang.NullPointerException error

I get this error when call Progress_Limits method in Fragment below , How initialize Fragment properly?

LogCat

09-05 06:37:30.075: E/AndroidRuntime(8676): FATAL EXCEPTION: main
09-05 06:37:30.075: E/AndroidRuntime(8676): Process: developer.mohab.gymee, PID: 8676
09-05 06:37:30.075: E/AndroidRuntime(8676): java.lang.RuntimeException: Unable to start activity ComponentInfo{developer.mohab.gymee/developer.mohab.gymee.Cardio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.support.v4.app.FragmentActivity.getContentResolver()' on a null object reference
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2345)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2405)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.access$800(ActivityThread.java:149)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.os.Looper.loop(Looper.java:211)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.main(ActivityThread.java:5333)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at java.lang.reflect.Method.invoke(Native Method)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at java.lang.reflect.Method.invoke(Method.java:372)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
09-05 06:37:30.075: E/AndroidRuntime(8676): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.support.v4.app.FragmentActivity.getContentResolver()' on a null object reference
09-05 06:37:30.075: E/AndroidRuntime(8676):     at developer.mohab.gymee.Cardio.Progress.getCursor(Progress.java:70)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at developer.mohab.gymee.Cardio.Progress.Prgress_Limits(Progress.java:43)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at developer.mohab.gymee.Cardio.MainActivity.onCreate(MainActivity.java:55)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.Activity.performCreate(Activity.java:5933)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
09-05 06:37:30.075: E/AndroidRuntime(8676):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
09-05 06:37:30.075: E/AndroidRuntime(8676):     ... 10 more

Fragment contain method i want call

public  class Progress extends Fragment {
TextView Abs ;
TextView Per ;
MainActivity mainActivity ;
Database database ;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mainActivity = (MainActivity) getActivity();
    database = new Database(getActivity());
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.progress,container,false);
    Abs = (TextView) view.findViewById(R.id.above);
    Per = (TextView) view.findViewById(R.id.below);
    Prgress_Limits();
    return view ;
}
public  void Prgress_Limits(){
    Cursor cursor ;
    cursor = getCursor();
    int LAST_INPUT ;
    int FIRST_INPUT ;
    if(cursor!=null&&cursor.moveToFirst()) {
        Log.e("mohab", "cursor not null");
        int VALUE_COLUMN = cursor.getColumnIndex(Contract.Cardio_chart.Values.VALUE);
        FIRST_INPUT = cursor.getInt(VALUE_COLUMN);
        cursor.moveToLast();
        LAST_INPUT = cursor.getInt(VALUE_COLUMN);
        int abs = LAST_INPUT-FIRST_INPUT ;
        Abs.setText(""+abs);
        int per = (abs*100)/FIRST_INPUT ;
        Per.setText(""+per+" %");
    }
    else {

        Abs.setText("null");

        Per.setText("null");
    }


}
public Cursor getCursor() {
    Cursor c;
    String Selection;
    Cursor check;
    ContentResolver hesolver = getActivity().getContentResolver();
    check = hesolver.query(DatabaseFilter.ValueTable(), null, null, null, null);
    Cursor check2;
    ContentResolver resolver = getActivity().getContentResolver();
    check2 = resolver.query(DatabaseFilter.LimitTable(), null, null, null, null);
    if (check != null && check.moveToFirst() && check2 != null && check2.moveToFirst()) {
        int Offset = offset();
        int Limit = limit();
        Selection = "SELECT * FROM " + DatabaseFilter.valueTable_Name() + " LIMIT " + Limit + " OFFSET " + Offset + ";";
        SQLiteDatabase db = database.getReadableDatabase();
        c = db.rawQuery(Selection, null);
    } else {
        ContentResolver sesolver = getActivity().getContentResolver();
        c = sesolver.query(DatabaseFilter.ValueTable(), null, null, null, null);
    }
    return c;
}
public int offset() {
    Cursor save;
    ContentResolver resolver = getActivity().getContentResolver();
    save = resolver.query(DatabaseFilter.LimitTable(), null, null, null, null);
    save.moveToLast();
    int high = save.getColumnIndex(Contract.Cardio_chart.Limits.HIGH);
    int Offset = save.getInt(high);
    save.close();
    return Offset;
}

public int limit() {

    Cursor h;
    ContentResolver resolver = getActivity().getContentResolver();
    h = resolver.query(DatabaseFilter.ValueTable(), null, null, null, null);
    h.moveToLast();
    int id = h.getColumnIndex(Contract.Cardio_chart.Values._ID);
    int last_chart_input = h.getInt(id);
    int Offset = offset();
    int Limit = last_chart_input - Offset;
    h.close();
    return Limit;
}

}

How i instantiate Fragment and call Progress_Limits Methode From Activity

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     p = new Progress();
    getSupportFragmentManager().beginTransaction()
            .add(R.id.group, p)
            .commit();
    p.Prgress_Limits();
    database = new Database(this) ;
    setSpinner();
    addEntries(0, 0, true);
    addPlus();


}

Upvotes: 1

Views: 572

Answers (2)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

Here:

p.Prgress_Limits();  //<<<<
database = new Database(this) ;

p.Prgress_Limits() causing issue becuase this method is called just after calling commit() method,which means probably Fragment is not ready. so call of getActivity() returning null.

To fix this issue call p.Prgress_Limits(); in onResume of Activity or use Handler to make some delay in accessing methods from live Fragment

Upvotes: 1

stallianz
stallianz

Reputation: 185

The recommended and easiest way to communicate with fragments is with interfaces.

Define a interface in your activity, and let your fragment implement that interface.

Example:

To declare a interface

public interface ActivityToFragment{ void executeMethodInFragment(); }

And in your activity, declare a variable for this interface,

private ActivityToFragment mListener;

Now tie the listener to fragment

p = mListener

now implement the interface in your fragment

public  class Progress extends Fragment implements ActivityToFragment

Upvotes: 0

Related Questions