简体   繁体   中英

NullPointerException on getString with Bundle for an Android fragment

I try to get mysql db information and display the info in a fragment by clicking on an item in a navigation view, for that I use Bundle().

Here is my MainActivity :

String JSON_STRING;

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

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

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

        displayView(R.id.nav_random);
    }


    public void displayView(int viewId) {

        Fragment fragment = null;
        String title = getString(R.string.app_name);

        switch (viewId) {
            case R.id.nav_random:
                fragment = new Random();
                title = "RANDOM";
                break;
            case R.id.nav_podium:
                fragment = new Podium();
                title = "PODIUM";
                break;
            case R.id.nav_sport:
                fragment = new Sport();
                title = "SPORT";
                break;
            case R.id.nav_videogames:
                fragment = new Games();
                title = "GAMES";
                break;
            case R.id.nav_socialnetwork:
                fragment = new SocialNetwork();
                title = "SOCIAL NETWORKS";
                break;
            case R.id.nav_heart:
                fragment = new Heart();
                title = "FAVORITES";
                break;

        }

        if (fragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

            if (fragment instanceof Podium) {

                //Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
                new BackgroundTask().execute();
                Bundle args = new Bundle();
                args.putString("JSON_DATA", getIntent().getExtras().getString(JSON_STRING));
                fragment.setArguments(args);
            }

            ft.replace(R.id.content_frame, fragment);
            ft.commit();
        }

        // set the toolbar title
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("Mon titre");
        }

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

    }

    @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) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent myIntent = new Intent(getApplicationContext(), FacebookConnectActivity.class);
            startActivityForResult(myIntent, 0);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        displayView(item.getItemId());
        return true;
    }





    class BackgroundTask extends AsyncTask<Void, Void, String> {

        String json_url;

        @Override
        protected void onPreExecute() {

            json_url = "http://firejackal.fr/script.php";
        }

        @Override
        protected String doInBackground(Void... params) {

            try {
                URL url = new URL(json_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                while ((JSON_STRING = bufferedReader.readLine()) != null) {
                    stringBuilder.append(JSON_STRING + "\n");
                }

                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

    }

And here is my Fragment "Podium" code :

String JSON_STRING;
    JSONObject jsonObject;
    JSONArray jsonArray;
    ContactAdapter contactAdapter;
    ListView listView;


    public Podium() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_podium,null);

        listView = (ListView) v.findViewById(R.id.listview);

        Bundle args = getArguments();
        JSON_STRING = args.getString("JSON_DATA");

        contactAdapter = new ContactAdapter(this.getContext(),R.layout.row_layout);
        listView.setAdapter(contactAdapter);

        try {
            jsonObject = new JSONObject(JSON_STRING);
            jsonArray = jsonObject.getJSONArray("server_response");
            int count = 0;
            String id_user_post, place_post, date_post;

            while(count < jsonArray.length()){

                JSONObject JO = jsonArray.getJSONObject(count);
                id_user_post = JO.getString("id_user_post");
                place_post = JO.getString("place_post");
                date_post = JO.getString("date_post");

                Contacts contacts = new Contacts(id_user_post, place_post, date_post);
                contactAdapter.add(contacts);
                count++;

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        // Inflate the layout for this fragment
        return v;
    }

I have a NullPointerException :

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                      at fr.djey.trollstory.MainPageActivity.displayView(MainPageActivity.java:106)
                                                                      at fr.djey.trollstory.MainPageActivity.onNavigationItemSelected(MainPageActivity.java:162)

on these 2 lines in MainActivity :

args.putString("JSON_DATA", getIntent().getExtras().getString(JSON_STRING));

and

displayView(item.getItemId());

But I don't understand why, because I execute the AsyncTask clicking on the item Podium, and so JSON_STRING shouldn't be null?

EDIT

If I try args.putString("JSON_DATA", JSON_STRING);

I get this error :

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()'

On this line in the fragment :

jsonObject = new JSONObject(JSON_STRING);

looks like it's being thrown in this line:

args.putString("JSON_DATA", getIntent().getExtras().getString(JSON_STRING));

The exception is saying that the Bundle stored at getIntent.getExtras() is null. Where is that bundle added to the intent?

Try this code. Let me know if this doesn't work for you.

Bundle bundle= getIntent().getExtras;
Bundle args = new Bundle();
args.putString("JSON_DATA", bundle.getString(JSON_STRING));
fragment.setArguments(args);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM