带有Bundle的getString的NullPointerException用于Android片段

时间:2016-03-23 13:34:57

标签: java android android-fragments android-bundle

我尝试获取mysql数据库信息并通过单击导航视图中的项目在片段中显示信息,因为我使用了Bundle()。

这是我的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);
        }

    }

这是我的片段&#34;讲台&#34;代码:

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;
    }

我有一个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)
在MainActivity的这两行上

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

displayView(item.getItemId());

但是我不明白为什么,因为我执行AsyncTask点击项目Podium,所以JSON_STRING不应该为空?

修改

如果我尝试 args.putString("JSON_DATA", JSON_STRING);

我收到此错误:

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

在片段中的这一行:

jsonObject = new JSONObject(JSON_STRING);

2 个答案:

答案 0 :(得分:0)

看起来好像被抛入这一行:

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

例外情况是存储在getIntent.getExtras()的Bundle为空。该捆绑包添加到意图中的哪个位置?

答案 1 :(得分:0)

试试这段代码。如果这对您不起作用,请告诉我。

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