2016-03-23 9 views
0

Ich versuche, mysql db Informationen zu erhalten und die Informationen in einem Fragment anzuzeigen, indem Sie auf ein Element in einer Navigationsansicht klicken, dafür verwende ich Bundle().NullPointerException auf getString mit Bundle für ein Android-Fragment

Hier ist meine 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); 
     } 

    } 

Und hier ist mein 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; 
    } 

Ich habe eine Nullpointer:

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) 

auf diesen 2 Zeilen in MainActivity:

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

und

displayView(item.getItemId()); 

Aber ich verstehe nicht, warum, weil ich das AsyncTask Klick auf das Element Podium, auszuführen und JSON_STRING sollte so nicht sein Null?

EDIT

Wenn ich versuche,args.putString("JSON_DATA", JSON_STRING);

ich diesen Fehler:

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

Auf dieser Linie im Fragment:

jsonObject = new JSONObject(JSON_STRING); 
+1

JSON_STRING wird null, wenn der Leser das Lesen beendet hat. Sie überprüfen dies selbst hier: 'while ((JSON_STRING = bufferedReader.readLine())! = Null)'. Wenn JSON_STRING nicht null wird, wäre dies eine Endlosschleife. Ich denke jedoch, dass deine NPE auftritt, weil du etwas von den beabsichtigten Extras bekommst, von denen ich bezweifle, dass sie gesetzt sind, da deine Aktivität "MainActivity" heißt. Meistens ist das die erste Aktivität. – 0xDEADC0DE

+0

Ja, Sie haben Recht, haben Sie eine Idee, das zu lösen? – Jey10

+0

Verwenden Sie nicht getIntent(). GetExtras(). GetString. Einfach setzen Sie Ihre Zeichenfolge in das Bündel – 0xDEADC0DE

Antwort

0

sieht aus wie es in dieser Linie geworfen:

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

Die Ausnahme wird sagen, dass das Bundle bei getIntent.getExtras() gespeichert ist null. Wo wird dieses Bündel zur Absicht hinzugefügt?

0

Versuchen Sie diesen Code. Lass es mich wissen, wenn das nicht für dich funktioniert.

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

Ich werde versuchen, danke – Jey10

+0

getIntent konnte nicht mit Ihrem Code gelöst werden – Jey10

+0

Antwort wurde bearbeitet –

Verwandte Themen