1

i have activity with list that get the data from firebase, i have menu item that uncheck all the checkboxes. its work fine when first get to the activity but while i exit the app from this activity and the app goes to sleep when i return to app i get

Exception java.lang.NullPointerException: Attempt to write to field 'int android.app.Fragment.mNextAnim' on a null object reference android.app.BackStackRecord.run (BackStackRecord.java:779) android.app.FragmentManagerImpl.execPendingActions (FragmentManager.java:1582) android.app.FragmentManagerImpl$1.run (FragmentManager.java:483) android.os.Handler.handleCallback (Handler.java:751) android.os.Handler.dispatchMessage (Handler.java:95) android.os.Looper.loop (Looper.java:154) android.app.ActivityThread.main (ActivityThread.java:6688) java.lang.reflect.Method.invoke (Method.java) com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1468) com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1358)

i tried to understand why i get the null but didnt succed, i debug my app and the problem is in the function setIconPercent()

my activity:

package com.nadav.weddingcalc.activity_best_list;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;


import com.joanfuentes.hintcase.HintCase;
import com.joanfuentes.hintcase.RectangularShape;
import com.joanfuentes.hintcaseassets.hintcontentholders.SimpleHintContentHolder;
import com.joanfuentes.hintcaseassets.shapeanimators.RevealRectangularShapeAnimator;
import com.joanfuentes.hintcaseassets.shapeanimators.UnrevealRectangularShapeAnimator;
import com.nadav.weddingcalc.R;
import com.squareup.picasso.Picasso;

public class ActivityBest extends AppCompatActivity {
    static ListView lv;
    private AdapterActivityBest adapterActivityBest;
    DatabaseReference mDatabase;
    FirebaseUser user;
    static private FirebaseAuth auth;
    DatabaseReference myRef;
    static AdView mAdView;
    public  String numOfRows;
    MenuItem it;
    Menu men;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_activity_place);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        final ProgressBar pBar = (ProgressBar) findViewById(R.id.progresbar);
        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().
                addTestDevice(getString(R.string.ad_test_device_nexus5x))
                .addTestDevice("0E9830DF43C4EB440157B8C079727CF9")
                .build();
        mAdView.loadAd(adRequest);

        auth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance().getReference();
        user = auth.getCurrentUser();
        lv = (ListView) findViewById(R.id.lv);
        adapterActivityBest = new AdapterActivityBest(getApplicationContext()  ,lv, this);
         FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
         fab.setVisibility(View.INVISIBLE);

        lv.setAdapter(adapterActivityBest);


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                FirebaseDatabase database = FirebaseDatabase.getInstance();
                FirebaseUser user = auth.getCurrentUser();
                myRef = database.getReference("users");
                myRef.child(user.getUid()).child("list Best").orderByChild("orderNum").addValueEventListener(new ValueEventListener() {

                    @Override
                    public void onDataChange(DataSnapshot snapshot) {
                        adapterActivityBest.removeAllll();
                        adapterActivityBest.notifyDataSetChanged();

                        if (!snapshot.hasChildren()) {

                            auth = FirebaseAuth.getInstance();
                            mDatabase = FirebaseDatabase.getInstance().getReference();
                            FirebaseUser user = auth.getCurrentUser();

                            String[] temp = getResources().getStringArray(R.array.Best_list);

                            int[] arrDividers = {0,5,10,18,24,31,37,46};
                            int[] arrSectors = {1,4,6,7,8,9,11,12,13,14,15,17,19,23,25,27,29,39,43,49,50,51,52};

                            for(int i=0; i<=55 ; i++){
                                boolean flag = false;
                                for(int j=0; j<=22; j++) {
                                    if (i == arrSectors[j]) {
                                        ObjectActivityBest ob = new ObjectActivityBest("false", temp[i], i, "sector");
                                        mDatabase.child("users").child(user.getUid()).child("list Best").child(ob.name+"").setValue(ob);
                                        flag = true;
                                    }
                                }
                                for(int j=0; j<=7; j++) {
                                    if (i == arrDividers[j]) {
                                        ObjectActivityBest ob = new ObjectActivityBest("false", temp[i], i, "divider");
                                        mDatabase.child("users").child(user.getUid()).child("list Best").child(ob.name+"").setValue(ob);
                                        flag = true;
                                    }
                                }
                                if(!flag){
                                ObjectActivityBest ob = new ObjectActivityBest("false", temp[i], (i), "item");
                                    mDatabase.child("users").child(user.getUid()).child("list Best").child(ob.name+"").setValue(ob);
                                }
                            }


                        } else {

                            int countchecks=0;
                            FirebaseDatabase database = FirebaseDatabase.getInstance();
                            FirebaseUser user = auth.getCurrentUser();
                            myRef = database.getReference("users");
                            for (DataSnapshot messageSnapshot : snapshot.getChildren()) {

                                String name = (String) messageSnapshot.child("name").getValue();
                                String check = (String) messageSnapshot.child("check").getValue();
                                int orderNum = ((Long) messageSnapshot.child("orderNum").getValue()).intValue();
                                String sector = (String) messageSnapshot.child("sector").getValue();


                                    ObjectActivityBest e = new ObjectActivityBest(check, name, orderNum, sector);
                                switch(e.sector){
                                    case "sector":
                                        switch(e.name){
                                            case "צלם":
                                                e.name = "בחירת צלם";
                                                mDatabase.child("users").child(user.getUid()).child("list Best").child(e.orderNum+"").setValue(e);
                                                break;
                                            case "קייטרינג":
                                                e.name = "בחירת קייטרינג";
                                                mDatabase.child("users").child(user.getUid()).child("list Best").child(e.orderNum+"").setValue(e);
                                                break;
                                            case "דיגיי":
                                                e.name = "בחירת תקליטן";
                                                mDatabase.child("users").child(user.getUid()).child("list Best").child(e.orderNum+"").setValue(e);
                                                break;
                                        }
                                        adapterActivityBest.addSectionHeaderItem(e);
                                        break;
                                    case "divider":
                                        adapterActivityBest.addDividerHeaderItem(e);
                                        break;
                                    default:
                                        adapterActivityBest.addItem(e);
                                        break;
                                }
                                if(e.check.equals("true")){
                                    if(e.name.equals("בחירת אולם")){
                                        countchecks= countchecks+20;
                                    }else{
                                        if((e.orderNum>0&&e.orderNum<=9)){
                                            countchecks+=5;
                                        }else if(e.orderNum>=11 && e.orderNum<=15){
                                            countchecks+=2;
                                        }else{
                                            countchecks++;

                                        }
                                    }
                                }
                            }

                            setIconPercent(countchecks);



                        }

                        pBar.setVisibility(View.INVISIBLE);

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                });
//                launchAutomaticHint();
            }
        }, 0);

    }

    private void setIconPercent(int countchecks) {

    TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);

    it = men.findItem(R.id.action_check);

    it.setIcon(ContextCompat.getDrawable(getApplicationContext(),  imgs.getResourceId(countchecks/5, -1)));
    imgs.recycle();
    if(countchecks%5==0){
        it = men.findItem(R.id.action_text);
        it.setVisible(false);
        it = men.findItem(R.id.action_check);
        it.setVisible(true);
    }else{
        it = men.findItem(R.id.action_check);
        it.setVisible(false);
        it = men.findItem(R.id.action_text);
        it.setVisible(true);
        it.setTitle(countchecks+"%");
    }




    }


    public void makeTextLong(String s){
        Context context = getApplicationContext();
        Toast.makeText(context,s,Toast.LENGTH_LONG).show();
    }

    public Menu getMen() {
        return men;
    }

    public MenuItem getIt() {
        return it;
    }

    public String getNumOfRows() {
        return numOfRows;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        getMenuInflater().inflate(R.menu.percentage_menu, menu);
        men = menu;

        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(com.nadav.weddingcalc.R.menu.percentage_menu, menu);
        men = menu;
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        android.app.Fragment fragment = null;
        //noinspection SimplifiableIfStatement
        switch (id) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
//                try{
//                    this.finish();
//                }catch(Exception e){
//                    makeTextLong("crash");
//                }
                return true;

            default:
                return super.onOptionsItemSelected(item);

        }

    }
}
nadav tamim
  • 76
  • 10
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Atef Hares Mar 03 '17 at 14:13
  • are you serious my friend? i know is NullPointerException, in my case i dont understand why i get NullPointerException, why when i back to app the menu item dont found – nadav tamim Mar 03 '17 at 14:22
  • yes I am serious my friend, if you really know what is `NullPointerException` then you would probably debug your code and see what has caused the variable to be null and you would also mentioned that you tried but didn't succeed to find the cause! – Atef Hares Mar 03 '17 at 14:27

1 Answers1

0

You got this null pointer because you doesn't maintain a stack for the fragments. While you resume your activity the instance of the fragments destroyed and it is not reinitialized. So you need to maintain the fragment stack and check for the fragment stack if it is null

UserSharma
  • 458
  • 6
  • 20