2014-10-15 2 views
0

Мне нужна помощь. Я провел несколько подробных поисков в течение последних 4 часов, и я не уверен, что это связано с тем, что у меня есть ошибки в моем коде, или если я не делаю что-то правильно. В принципе, это то, что происходит. У меня есть моя главная работа «домашняя страница», которая открывает второе действие с помощью навигационного ящика. Я предполагаю, что навигационный ящик также является «активностью». Я пытаюсь открыть фрагмент в рамках этой деятельности с помощью кнопки, но я получаю фатальное исключение:Открытие фрагмента кнопкой

10-14 21:36:54.469  799-799/com.example.workstation.app E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workstation.app/com.example.workstation.app.navigation_drawer}: java.lang.NullPointerException 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) 
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) 
      at android.app.ActivityThread.access$600(ActivityThread.java:141) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 
      at android.os.Handler.dispatchMessage(Handler.java:99) 
      at android.os.Looper.loop(Looper.java:137) 
      at android.app.ActivityThread.main(ActivityThread.java:5103) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:525) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
      at dalvik.system.NativeStart.main(Native Method) 
    Caused by: java.lang.NullPointerException 
      at com.example.workstation.app.navigationdrawer.onCreate(navigationdrawer.java:57) 

Вот код, я работаю с, это один является для navigation_drawer деятельности (я считаю):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context="com.example.workstation.app.navigation_drawer_activity$PlaceholderFragment"> 

    <TextView 
     android:id="@+id/cctr_ct_home" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/cctr_ct" 
     android:textSize="40sp" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" /> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/cctr_search" 
     android:drawableTop="@drawable/search" 
     android:layout_below="@+id/cctr_ct_home" 
     android:layout_alignLeft="@+id/cctr_ct_home" 
     android:layout_alignStart="@+id/cctr_ct_home" 
     android:layout_marginTop="95dp" 
     android:text="Search"/> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/cctr_favorites" 
     android:drawableTop="@drawable/favorites" 
     android:layout_alignTop="@+id/cctr_search" 
     android:layout_alignRight="@+id/cctr_ct_home" 
     android:layout_alignEnd="@+id/cctr_ct_home" 
     android:text="Favorite"/> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/cctr_recent" 
     android:drawableTop="@drawable/recent" 
     android:layout_below="@+id/cctr_search" 
     android:layout_alignLeft="@+id/cctr_search" 
     android:layout_alignStart="@+id/cctr_search" 
     android:layout_marginTop="37dp" 
     android:text="Recent"/> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/cctr_contactus" 
     android:drawableTop="@drawable/email" 
     android:layout_alignTop="@+id/cctr_recent" 
     android:layout_alignLeft="@+id/cctr_favorites" 
     android:layout_alignStart="@+id/cctr_favorites" 
     android:text="Contact Us" /> 

    <fragment android:name="com.example.workstation.cctrmobileapp.cctrct_search" 
     android:id="@+id/cctr_ct_search" 
     android:layout_weight="2" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" /> 

</RelativeLayout> 

Теперь ящик для навигации отлично работает, он открывает фрагмент с кнопки, с которой у меня возникают проблемы. Я получаю ошибку выше. Вот ява код от деятельности, которая поставляется с навигационной панели:

package com.example.workstation.cctrmobileapp; 

import android.app.Activity; 
import android.support.v4.app.FragmentTransaction; 
import android.content.Intent; 
import android.net.Uri; 
import android.support.v4.app.FragmentActivity; 
import android.support.v7.app.ActionBarActivity; 
import android.support.v7.app.ActionBar; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.content.Context; 
import android.os.Build; 
import android.os.Bundle; 
import android.view.Gravity; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.support.v4.widget.DrawerLayout; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.TextView; 


public class cctr_clinical_trials extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, cctrct_search.OnFragmentInteractionListener { 

    /** 
    * Fragment managing the behaviors, interactions and presentation of the navigation drawer. 
    */ 
    private NavigationDrawerFragment mNavigationDrawerFragment; 

    /** 
    * Used to store the last screen title. For use in {@link #restoreActionBar()}. 
    */ 
    private CharSequence mTitle; 

    Button cctrct_searchButton; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_cctr_clinical_trials); 

     mNavigationDrawerFragment = (NavigationDrawerFragment) 
       getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); 
     mTitle = getTitle(); 

     // Set up the drawer. 
     mNavigationDrawerFragment.setUp(
       R.id.navigation_drawer, 
       (DrawerLayout) findViewById(R.id.drawer_layout)); 

     cctrct_searchButton = (Button)findViewById(R.id.cctr_search); 

     cctrct_searchButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       cctrct_search newFragment = new cctrct_search(); 
       FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 

       transaction.replace(R.id.container, newFragment); 
       transaction.addToBackStack(null); 

       transaction.commit(); 

      } 
     }); 

/*  cctrct_searchButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       FragmentManager searchFragment = getSupportFragmentManager(); 

       searchFragment.beginTransaction() 

         .replace(R.id.container, cctrct_search.newInstance("test1", "test2")) 

         .commit(); 
      } 

     });*/ 


    } 

и щеколду этого, здесь есть XML-файл для фрагмента, который я хочу, чтобы появиться после нажатия кнопки:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.example.workstation.cctrmobileapp.cctrct_search"> 

    <!-- TODO: Update blank fragment layout --> 

<RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Submit" 
     android:id="@+id/cctrct_search_submit" 
     android:layout_below="@+id/cctrct_p1" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="65dp" 
     android:layout_gravity="center_horizontal|bottom" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="Only the submit button works" 
     android:id="@+id/cctr_search_logo" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="43dp" 
     android:layout_gravity="center_horizontal|top" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Phase III" 
     android:id="@+id/cctrct_p3" 
     android:layout_toEndOf="@+id/cctrct_search_dsite" 
     android:layout_below="@+id/cctrct_search_pnum" 
     android:layout_toRightOf="@+id/cctrct_search_dsite" 
     android:layout_marginTop="28dp" 
     android:layout_gravity="center" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Phase II" 
     android:id="@+id/cctrct_p2" 
     android:layout_toEndOf="@+id/cctrct_p1" 
     android:layout_alignTop="@+id/cctrct_p3" 
     android:layout_alignLeft="@+id/cctrct_search_keyword" 
     android:layout_alignStart="@+id/cctrct_search_keyword" 
     android:layout_alignRight="@+id/cctrct_search_dsite" 
     android:layout_alignEnd="@+id/cctrct_search_dsite" 
     android:layout_gravity="center" /> 

    <RadioButton 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Phase I" 
     android:id="@+id/cctrct_p1" 
     android:layout_toStartOf="@+id/cctrct_search_pnum" 
     android:layout_alignTop="@+id/cctrct_p2" 
     android:layout_toLeftOf="@+id/cctrct_search_pnum" 
     android:layout_gravity="center" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="Keyword" 
     android:id="@+id/cctrct_search_keyword" 
     android:layout_below="@+id/cctrct_search_dsite" 
     android:layout_alignRight="@+id/cctrct_search_submit" 
     android:layout_alignEnd="@+id/cctrct_search_submit" 
     android:layout_marginTop="26dp" 
     android:layout_gravity="left|center_vertical" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="Disease Site" 
     android:id="@+id/cctrct_search_dsite" 
     android:layout_below="@+id/cctr_search_logo" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="22dp" 
     android:layout_gravity="right|center_vertical" /> 

    <EditText 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="Protocol Number" 
     android:id="@+id/cctrct_search_pnum" 
     android:layout_below="@+id/cctrct_search_keyword" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="31dp" 
     android:layout_gravity="left|center_vertical" /> 

</RelativeLayout> 

</FrameLayout> 

Я просто полагал, что я хотел бы добавить остальную часть кода из моего класса:

@Override 
    public void onNavigationDrawerItemSelected(int position) { 
     // update the main content by replacing fragments 
     FragmentManager fragmentManager = getSupportFragmentManager(); 

     switch (position) { 
      case 0: fragmentManager.beginTransaction() 
        .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) 
        .commit(); break; 
      case 1: fragmentManager.beginTransaction() 
        .replace(R.id.container, cctrct_search.newInstance("test1", "test2")) 
        .commit(); break; 
      case 2: fragmentManager.beginTransaction() 
        .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) 
        .commit(); break; 
      case 3: fragmentManager.beginTransaction() 
        .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) 
        .commit(); break; 
     } 

    } 

    public void onSectionAttached(int number) { 
     switch (number) { 
      case 1: 
       mTitle = getString(R.string.cctr_ct_home); 
       break; 
      case 2: 
       mTitle = getString(R.string.cctr_ct_search); 
       break; 
      case 3: 
       mTitle = getString(R.string.cctr_ct_saved); 
       break; 
      case 4: 
       mTitle = getString(R.string.cctr_ct_recent); 
       break; 
     } 
    } 

    public void restoreActionBar() { 
     ActionBar actionBar = getSupportActionBar(); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); 
     actionBar.setDisplayShowTitleEnabled(true); 
     actionBar.setTitle(mTitle); 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     if (!mNavigationDrawerFragment.isDrawerOpen()) { 
      // Only show items in the action bar relevant to this screen 
      // if the drawer is not showing. Otherwise, let the drawer 
      // decide what to show in the action bar. 
      getMenuInflater().inflate(R.menu.cctr_clinical_trials, menu); 
      restoreActionBar(); 
      return true; 
     } 
     return super.onCreateOptionsMenu(menu); 
    } 

    @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(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    public void onFragmentInteraction(Uri uri) { 

    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 
     private static final String ARG_SECTION_NUMBER = "section_number"; 

     /** 
     * Returns a new instance of this fragment for the given section 
     * number. 
     */ 
     public static PlaceholderFragment newInstance(int sectionNumber) { 
      PlaceholderFragment fragment = new PlaceholderFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
      fragment.setArguments(args); 
      return fragment; 
     } 

     public PlaceholderFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_cctr_clinical_trials, container, false); 
      return rootView; 
     } 

     @Override 
     public void onAttach(Activity activity) { 
      super.onAttach(activity); 
      ((cctr_clinical_trials) activity).onSectionAttached(
        getArguments().getInt(ARG_SECTION_NUMBER)); 
     } 



    } 

} 
+0

Здесь находятся подобные вопросы: http://stackoverflow.com/questions/12811496/starting-fragment-from-button-in-another-fragment и HTTP://stackoverflow.com/questions/14983738/button-open-a-fragment – Alexey

+0

Можете ли вы разместить свой код navigationdrawer.java? Он говорит, что NullPointerException происходит по строке 57 – Spidy

+0

Это на самом деле код выше. Я пытался изменить некоторые строки, но в конце концов, я понял, что их было слишком много ... поэтому я просто оставил их ... Это в основном указывает на: ** cctrct_searchButton.setOnClickListener (новый вид. OnClickListener() ** – mastawu

ответ

0

похоже cctrct_searchButton является нулевой, что означает, что не найден в вид. Есть кнопка с идентификаторомcctr_searchприсутствует вactivity_cctr_clinical_trialsмакет xml файл?

+0

Activity_cctr_clinical_trials.xml содержит только элементы, необходимые для ящика для навигации. Нужно ли добавлять новый фрагмент с "id =" cctr_search "?? Я мог ли разместить фрагмент в неправильном xml? он в файле fragment_cctr_clinical_trials.xml – mastawu

+0

Ваши cctr_clinical_trials раздуты activity_cctr_clinical_trials, что означает, что он имеет доступ только к представлениям на этом макете. Технически вы можете получить доступ к кнопкам на фрагментах, но только после добавления фрагментов.И фрагменты не добавляются сразу (если вы не вызываете executePendingTransactions). Итак, вопрос в том, где эти кнопки вы пытаетесь нажать? – Spidy

+0

sphanley, я не уверен, с кем вы разговариваете, но ваш комментарий очень непродуктивен. – Spidy

0

Для будущих пользователей, г-н Паучок был 100% правильно, onClickListener должен был в onCreateView, а не в OnCreate разделе:

public PlaceholderFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_cctr_clinical_trials, container, false); 


      Button cctrct_searchButton; 

      cctrct_searchButton = (Button)rootView.findViewById(R.id.cctr_search); 

      cctrct_searchButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 

        Fragment newFragment = new cctrct_search(); 
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction(); 

        transaction.replace(R.id.container, newFragment); 
        transaction.addToBackStack(null); 

        transaction.commit(); 
       } 
      }); 

      return rootView; 

     } 

БЛАГОДАРЯ СНОВА MR. Паучок

Смежные вопросы