0

我已經做了一個Android應用程序,在我第一次登錄,然後顯示一個具有導航抽屜的主要活動。導航抽屜有Home和Profile。家庭顯示一個倒數計時器,而配置文件從數據庫中檢索信息並顯示它。 第一次main.class來到主頁並顯示倒計時。然後我轉到配置文件。配置文件頁面正確顯示。 現在這裏變得很難理解我。然後我回家(它顯示正確),然後配置文件,然後回家(現在有一個錯誤)通過片段循環的第三次迭代的錯誤

我無法弄清楚爲什麼會出現錯誤。請幫助。我是android編程的新手。

MenuFragment.java是顯示倒數的那個。 該錯誤是在第三次迭代線

TextView mTextField = (TextView)getActivity().findViewbById(R.id.welcome); 
MenuFragment.java的

這裏是main.class

public class Main extends Activity { 
private DrawerLayout mDrawerLayout; 
private ListView mDrawerList; 
private ActionBarDrawerToggle mDrawerToggle; 
private TextView mTextField; 
private CharSequence mDrawerTitle; 
private CharSequence mTitle; 
private String[] mMenuTitles; 

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

    mTitle = mDrawerTitle = getTitle(); 
    mMenuTitles = getResources().getStringArray(R.array.menu_array); 
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
    mDrawerList = (ListView) findViewById(R.id.left_drawer); 

    // set a custom shadow that overlays the main content when the drawer opens 
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); 
    // set up the drawer's list view with items and click listener 
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, 
      R.layout.drawer_list_item, mMenuTitles)); 
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); 

    // enable ActionBar app icon to behave as action to toggle nav drawer 
    getActionBar().setDisplayHomeAsUpEnabled(true); 
    getActionBar().setHomeButtonEnabled(true); 






    // ActionBarDrawerToggle ties together the the proper interactions 
    // between the sliding drawer and the action bar app icon 
    mDrawerToggle = new ActionBarDrawerToggle(
      this,     /* host Activity */ 
      mDrawerLayout,   /* DrawerLayout object */ 
      R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ 
      R.string.drawer_open, /* "open drawer" description for accessibility */ 
      R.string.drawer_close /* "close drawer" description for accessibility */ 
      ) { 
     public void onDrawerClosed(View view) { 
      getActionBar().setTitle(mTitle); 
      invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
     } 

     public void onDrawerOpened(View drawerView) { 
      getActionBar().setTitle(mDrawerTitle); 
      invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
     } 
    }; 
    mDrawerLayout.setDrawerListener(mDrawerToggle); 

    if (savedInstanceState == null) { 
     selectItem(0); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.main, menu); 
    return super.onCreateOptionsMenu(menu); 
} 

/* Called whenever we call invalidateOptionsMenu() */ 
@Override 
public boolean onPrepareOptionsMenu(Menu menu) { 
    // If the nav drawer is open, hide action items related to the content view 
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); 
    menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); 
    return super.onPrepareOptionsMenu(menu); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // The action bar home/up action should open or close the drawer. 
    // ActionBarDrawerToggle will take care of this. 
    if (mDrawerToggle.onOptionsItemSelected(item)) { 
     return true; 
    } 
    // Handle action buttons 
    switch(item.getItemId()) { 
    case R.id.action_websearch: 
     // create intent to perform web search for this planet 
     Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); 
     intent.putExtra(SearchManager.QUERY, getActionBar().getTitle()); 
     // catch event that there's no activity to handle intent 
     if (intent.resolveActivity(getPackageManager()) != null) { 
      startActivity(intent); 
     } else { 
      Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show(); 
     } 
     return true; 
    default: 
     return super.onOptionsItemSelected(item); 
    } 
} 

/* The click listner for ListView in the navigation drawer */ 
private class DrawerItemClickListener implements ListView.OnItemClickListener { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
    { 

     selectItem(position); 
    } 
} 
private void selectItem(int position) { 
    // update the main content by replacing fragments 

    if (position == 1) 
    { 
     Fragment fragment = new FragmentProfile(); 
     Bundle args = new Bundle(); 

     args.putInt(FragmentProfile.ARG_MENU_NUMBER, position); 
     fragment.setArguments(args); 

     FragmentManager fragmentManager = getFragmentManager(); 
     fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, "current_fragment").commit(); 
    } 
    else 
    { 

    Fragment fragment = new MenuFragment(); 
    Bundle args = new Bundle(); 
    args.putInt(MenuFragment.ARG_MENU_NUMBER, position); 
    fragment.setArguments(args); 

    FragmentManager fragmentManager = getFragmentManager(); 
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

    // update selected item and title, then close the drawer 



    //timer.cancel(); 

    } 
    mDrawerList.setItemChecked(position, true); 
    setTitle(mMenuTitles[position]); 
    mDrawerLayout.closeDrawer(mDrawerList); 
} 



@Override 
public void setTitle(CharSequence title) { 
    mTitle = title; 
    getActionBar().setTitle(mTitle); 
} 

/** 
* When using the ActionBarDrawerToggle, you must call it during 
* onPostCreate() and onConfigurationChanged()... 
*/ 

@Override 
protected void onPostCreate(Bundle savedInstanceState) { 
    super.onPostCreate(savedInstanceState); 
    // Sync the toggle state after onRestoreInstanceState has occurred. 
    mDrawerToggle.syncState(); 
} 



@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
    // Pass any configuration change to the drawer toggls 
    mDrawerToggle.onConfigurationChanged(newConfig); 
} 

/** 
* Fragment that appears in the "content_frame", shows a planet 
*/ 





} 

這裏是MenuFragment.java

public class MenuFragment extends Fragment { 
public static final String ARG_MENU_NUMBER = "menu_number"; 
public static boolean ifpause = false; 
public static boolean flag = false; 

public MenuFragment() { 

} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    int i = getArguments().getInt(ARG_MENU_NUMBER); 
    View rootView; 


      rootView = inflater.inflate(R.layout.fragment_menu, container, false); 




    String menu = getResources().getStringArray(R.array.menu_array)[i]; 
    TextView mTextField = (TextView)rootView.findViewById(R.id.welcome); 
    mTextField.setText("00:00:10"); 
    final CounterClass timer = new CounterClass(10000,1000); 
    timer.start(); 




    System.out.println(i); 
    getActivity().setTitle(menu); 
    return rootView; 
} 

public void onPause() 
{ 
    super.onPause(); 
    ifpause = true; 
} 
public void onResume() { 
    super.onResume(); 
    ifpause=false; 
    flag=true; 

} 

public class CounterClass extends CountDownTimer { 
    public CounterClass(long millisInFuture, long countDownInterval) 
    { 
     super(millisInFuture, countDownInterval); 
    } 
    public TextView mTextField = (TextView)getActivity().findViewById(R.id.welcome); 
    @Override 
    public void onFinish() 
    { 

     } 
    @Override 
    public void onTick(long millisUntilFinished) 
    { 

     long millis = millisUntilFinished; 
     String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), 
       TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), 
       TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); 

     if(!ifpause) 
     { 
      TextView mTextField = (TextView)getActivity().findViewById(R.id.welcome); 
      mTextField.setText(hms); 

     } 


    } 
} 



} 

logcat的

E/AndroidRuntime(4456): FATAL EXCEPTION: main 
E/AndroidRuntime(4456): Process: com.example.test, PID: 4456 
E/AndroidRuntime(4456): java.lang.NullPointerException 
E/AndroidRuntime(4456): at  com.example.test.MenuFragment$CounterClass.onTick(MenuFragment.java:108) 
E/AndroidRuntime(4456): at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:124) 
E/AndroidRuntime(4456): at android.os.Handler.dispatchMessage(Handler.java:102) 
E/AndroidRuntime(4456): at android.os.Looper.loop(Looper.java:136) 
E/AndroidRuntime(4456): at android.app.ActivityThread.main(ActivityThread.java:5017) 
E/AndroidRuntime(4456): at java.lang.reflect.Method.invokeNative(Native Method) 
E/AndroidRuntime(4456): at java.lang.reflect.Method.invoke(Method.java:515) 
E/AndroidRuntime(4456): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
E/AndroidRuntime(4456): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
E/AndroidRuntime(4456): at dalvik.system.NativeStart.main(Native Method) 

回答

1

我相信你已經有了一個競爭條件在這裏。

該片段可能與其父活動分離。完成後您需要取消定時器。可能在onDestroyView。

製作一個私有成員變量來保存您的計時器。在你的onCreateView方法中初始化它時使用它。然後,利用它在你重寫onDestroyView方法,像這樣:

private CounterClass timer; 

@Override 
public void onDestroyView() 
{ 
    super.onDestroyView(); 

    if (timer != null) 
    { 
     timer.cancel(); 
     timer = null; 
    } 
} 

此外,您可能要防範通過檢查getActivity您的片段沒有附着於你的onTick方法的活動()==在那種情況下返回null。

有關片段生命週期的更多信息,請看看這裏:

http://developer.android.com/reference/android/app/Fragment.html#Lifecycle

+0

感謝您的回答。我會盡力去做。還有另一個問題。當我在調試模式下使用MenuFragment.java中的幾個斷點運行它時,代碼似乎正常工作。任何想法爲什麼會發生這種事情?你能否解釋一下,或者如果可能的話,你能否提供一些參考鏈接來研究這種行爲? – kerry 2014-09-21 05:13:31

+0

這工作......謝謝 – kerry 2014-09-21 05:30:48

+0

我認爲你所要做的就是導航到,然後遠離這個片段來獲得崩潰。 – 2014-09-21 06:13:59

相關問題