0

Actually never asked for help here, before i was able to find it, but here is exceptional case. My app should get the json file (single one, basically static info), parse it and place it in the navigationDrawer in diffferent fragments . NavDrawer should be filled dynamically (json have three parameters, one of them is name of the single item), and content should be displayed in different fragments, and all of this should work on both orientations portrait, and landscape (state should be saved).

So i got NetworkOperations.java class in which i trying to get response from url where json file is placed, using enqueue() type of request. Because of this type, basically as i understand all my logic should in onResponse method, because in other case i would get NPE in the most of the cases because of async type of work of this request.

To save my data which is a List with my responsebody type i trying to transfer it, by intent. My problem is, that i got NullPointerException during getAplicationContext() (code below). Can, please, someone provide some help? onCreate method is proceding, as much as my App util method where retrofitBuilder is declared. In both cases theoratically context should appear, why i can't have it?

Thank you in advance, and sorry for my bad english.

EDIT: Here is a code which give NPE

Intent intent = new Intent(mContext.getApplicationContext() , 
MainActivity.class);

MainActivity.java

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

//Tags
private static final String TAG = "MainActivity";

//vars
private NetworkOperations operations = new NetworkOperations();
private List<com.example.coder.testapp.model.Menu> menuItemList = new ArrayList<>();
private ArrayList<com.example.coder.testapp.model.Menu> listForDrawer = new ArrayList<>();

//widgets


private NavigationView navigationView;
private ProgressBar mProgressBar;
private Menu menu;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    mProgressBar = findViewById(R.id.progress_bar);


    new DownloadTask().execute();

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == FragmentKeys.FRAGMENT_ONE) {

    } else if (id == FragmentKeys.FRAGMENT_TWO) {

    } else if (id == FragmentKeys.FRAGMENT_THREE) {

    } else if (id == FragmentKeys.FRAGMENT_FOUR) {

    }

    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void addNewItem (String itemName){
    menu = navigationView.getMenu();
    menu.add(Menu.NONE,Menu.NONE,Menu.NONE,itemName);
    System.out.println("Item " + itemName + " added" );
}

public void initDrawer(List<com.example.coder.testapp.model.Menu> list){
    System.out.println(list);
    if (list != null) {
        System.out.println(list.size());
        addNewItem(list.get(FragmentKeys.FRAGMENT_ONE).getName());
        addNewItem(list.get(FragmentKeys.FRAGMENT_TWO).getName());
        addNewItem(list.get(FragmentKeys.FRAGMENT_THREE).getName());
        addNewItem(list.get(FragmentKeys.FRAGMENT_FOUR).getName());
    }
}

private void getMenuList (){
    menuItemList = new ArrayList<>();
    operations.getResponses(menuItemList);
    Intent intent = new Intent(this, MainActivity.class);
    listForDrawer = intent.getParcelableArrayListExtra("menus");

    System.out.println("get menu list response " + menuItemList);
}

class DownloadTask extends AsyncTask<Void, Void, Void> {

    protected void onPreExecute() {
        Log.d(TAG, "onPreExecute: ");
        publishProgress(true);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        Log.d(TAG, "doInBackground: ...");
        getMenuList();
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        Log.d(TAG, "onPostExecute: completed...");
        initDrawer(listForDrawer);
        publishProgress(false);
    }

    public void publishProgress(boolean change){
        if (change) {
            mProgressBar.bringToFront();
            mProgressBar.setBackgroundColor(getResources().getColor(R.color.mainBackgroundblur));
            mProgressBar.setVisibility(View.VISIBLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        } else {
            mProgressBar.setVisibility(View.GONE);

            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

        }
    }
}

NetworkOperations.java

public class NetworkOperations {

private static final String TAG = "Network operations";

private ArrayList<Menu> menuList;
private Example mRespons;
private Context mContext;

public void getResponses(final List<Menu> list) {

    App.getServerAPI().getExample().enqueue(new Callback<Example>() {
        @Override
        public void onResponse(@NonNull Call<Example> call,
                               @NonNull Response<Example> response) {
            if (response.body()!= null) {
                mRespons = response.body();
                System.out.println("Response is not empty " + mRespons);
                if (mRespons != null) {
                    System.out.println(mRespons.getMenu() + " shit");
                    list.addAll(mRespons.getMenu());
                    menuList= new ArrayList<>();
                    menuList.addAll(list);
                    System.out.println("This is global " + menuList);
                    System.out.println("This is inner " + list);

                   if (menuList.size()>0) {
                       System.out.println(mContext.getApplicationContext().toString());
                       Intent intent = new Intent(mContext.getApplicationContext() , MainActivity.class);
                       intent.putParcelableArrayListExtra("menus", menuList);
                       System.out.println("OLA " + menuList);
                   }
                }
            }
        }
        @Override
        public void onFailure(Call<Example> call, Throwable t) {
            Toast.makeText(mContext, "An error occurred during networking", Toast.LENGTH_SHORT).show();
        }
    });
}

}

EDIT: error code

07-30 20:50:38.715 4751-4751/com.example.coder.testapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.coder.testapp, PID: 4751
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
    at com.example.coder.testapp.operations.NetworkOperations$1.onResponse(NetworkOperations.java:51)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:815)
    at android.os.Handler.dispatchMessage(Handler.java:104)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:5728)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
  • can you post error code snippet ? – iamkdblue Jul 30 '18 at 17:47
  • kdblue - i added snippet in edit section at the bottom – GracefulLeo Jul 30 '18 at 17:53
  • Apollogizing by asking here , but how does the answer from the question with which my is "duplicating" can answer on my question, if it is not about NPE nature, but about exactly specific case, which i describe? How does they correspond to each other, and what need to be done to solve it? Thank you in advance, and excuse me, i am new here (rules i read). – GracefulLeo Jul 30 '18 at 17:58
  • @GracefulLeo you have declared mContext but didn't assign value to it therefore it is giving NPE. Create a constructor of `NetworkOperations.java` as `public NetworkOperations(Context context){ this.mContext = context;}` and in your MainActivity.java modify your code as `//vars private NetworkOperations operations;` and in `onCreate` method initialize by calling `operations = new NetworkOperations(MainActivity.this);` Also, in `NetworkOperations.java` use only `mContext` instead of `mContext.getApplicationContext()` – Viraj Patel Jul 30 '18 at 18:00
  • NetworkOperations is a class , getApplicationContext() need activity context ! – iamkdblue Jul 30 '18 at 18:00
  • Viraj Patel - thank you! Your answer worked just perfect. Unfortunately i was need to rewrite that piece of code anyway but that's another story. Thank you once again! – GracefulLeo Jul 31 '18 at 14:39

0 Answers0