2015-11-14 5 views
0

Мое приложение не имеет erro в коде, однако приложение открыто и близко. Это что-то связано с id, layout?Приложение Android одновременно открывается и закрывается. Зачем?

import java.util.Locale; 
import android.app.Fragment; 
import android.app.FragmentManager; 
import android.app.SearchManager; 
import android.content.Intent; 
import android.content.res.Configuration; 
import android.content.res.TypedArray; 
import android.os.Bundle; 
import android.support.v4.app.ActionBarDrawerToggle; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.Toast; 


// Função principal do programa que extende fragmentos 
public class MainActivity extends FragmentActivity { 
    private DrawerLayout mDrawerLayout; 
    private ListView mDrawerList; 
    private ActionBarDrawerToggle mDrawerToggle; 

    private CharSequence mDrawerTitle; // CharSequence como o nome indica é uma sequencia de char, ou seja, texto 
    private CharSequence mTitle; // CharSequence como o nome indica é uma sequencia de char, ou seja, texto 
    private String[] mPlanetTitles; 
    private ImageView mIcon; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); // responsável por exibir a tela da minha aplicação , baseado nos layouts xml. 
     mTitle = mDrawerTitle = getTitle(); // Gets the title of the frame (String) 
     mPlanetTitles = getResources().getStringArray(R.array.planets_array); // Pela minha lista de string com o nome dos planetas 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle). 

     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 
     // ira colocar no list view localizado do drawer_layout, um layout do tipo drawer_list_item, usando os nomes dos planetas 
     mDrawerList.setAdapter(new ArrayAdapter<String>(this, 
       R.layout.drawer_list_icon, mPlanetTitles)); 
     //Registrar um callback para ser chamado quando um produto neste AdapterView foi clicado . 
     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.activity_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 { 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
         selectItem(position); 
     } 
    } 

    private void selectItem(int position) { 

     Fragment fragment = new PlanetFragment(); 
     Bundle args = new Bundle(); 
     FragmentManager fragmentManager = getFragmentManager(); 

     switch(position){ 
     case 0: 
      // update the main content by replacing fragments 
      args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
      fragment.setArguments(args); 
      fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

      // update selected item and title, then close the drawer 
      mDrawerList.setItemChecked(position, true); 
      setTitle(mPlanetTitles[position]); 
      mDrawerLayout.closeDrawer(mDrawerList); 
      Toast.makeText(this, String.valueOf(position), Toast.LENGTH_SHORT).show(); 
      break; 

     case 1: 
      // Capture the article fragment from the activity layout 
      //QuestionActivity articleFrag = (QuestionActivity) 
      //  getSupportFragmentManager().findFragmentById(R.id.FrameLayout1); 
      Fragment newfragment = new QuestionActivity(); 
      // update the main content by replacing fragments 
      args.putInt(QuestionActivity.ARG_POSITION, position); 
      newfragment.setArguments(args); 
      fragmentManager.beginTransaction().replace(R.id.content_frame, newfragment).commit(); 

      // update selected item and title, then close the drawer 
      mDrawerList.setItemChecked(position, true); 
      setTitle(mPlanetTitles[position]); 
      mDrawerLayout.closeDrawer(mDrawerList); 
      Toast.makeText(this, String.valueOf(position), Toast.LENGTH_SHORT).show(); 



      //FragmentManager fragmentManager1 = getFragmentManager(); 
      //Fragment frag1 =(Fragment) fragmentManager1.findFragmentById(R.id.); 
      //Bundle args1 = new Bundle(); 

      //Fragment frag1 =(Fragment) fragmentManager.findFragmentById(R.id.) 
      // This method will be executed once the timer is over 
      // Start your app main activity 
      // Intent i = new Intent(this, QuestionActivity.class); 
      // startActivity(i); 
      // close this activity 
      Toast.makeText(this, "Indicativo de acao ", Toast.LENGTH_SHORT).show(); 
      break; 

     case 2: 
      // update the main content by replacing fragments 
      args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
      fragment.setArguments(args); 
      fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

      // update selected item and title, then close the drawer 
      mDrawerList.setItemChecked(position, true); 
      setTitle(mPlanetTitles[position]); 
      mDrawerLayout.closeDrawer(mDrawerList); 
      Toast.makeText(this, String.valueOf(position), Toast.LENGTH_SHORT).show(); 
      break; 

     case 3: 
      // update the main content by replacing fragments 
      args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
      fragment.setArguments(args); 
      fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

      // update selected item and title, then close the drawer 
      mDrawerList.setItemChecked(position, true); 
      setTitle(mPlanetTitles[position]); 
      mDrawerLayout.closeDrawer(mDrawerList); 
      Toast.makeText(this, String.valueOf(position), Toast.LENGTH_SHORT).show(); 
      break; 

     case 4: 
      // update the main content by replacing fragments 
      args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
      fragment.setArguments(args); 
      fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

      // update selected item and title, then close the drawer 
      mDrawerList.setItemChecked(position, true); 
      setTitle(mPlanetTitles[position]); 
      mDrawerLayout.closeDrawer(mDrawerList); 
      Toast.makeText(this, String.valueOf(position), Toast.LENGTH_SHORT).show(); 
      break; 

     case 5: 
      // update the main content by replacing fragments 
      args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
      fragment.setArguments(args); 
      fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

      // update selected item and title, then close the drawer 
      mDrawerList.setItemChecked(position, true); 
      setTitle(mPlanetTitles[position]); 
      mDrawerLayout.closeDrawer(mDrawerList); 
      Toast.makeText(this, String.valueOf(position), Toast.LENGTH_SHORT).show(); 
      break; 

     case 6: 
      // update the main content by replacing fragments 
      args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
      fragment.setArguments(args); 
      fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

      // update selected item and title, then close the drawer 
      mDrawerList.setItemChecked(position, true); 
      setTitle(mPlanetTitles[position]); 
      mDrawerLayout.closeDrawer(mDrawerList); 
      Toast.makeText(this, String.valueOf(position), Toast.LENGTH_SHORT).show(); 
      break; 

     case 7: 
      // This method will be executed once the timer is over 
      // Start your app main activity 
      Intent j = new Intent(this, ScreenSplash.class); 
      startActivity(j); 
      // close this activity 
      finish(); 

      Toast.makeText(this, "Indicativo de acao ", Toast.LENGTH_SHORT).show(); 
      break;   
      }   
    } 




    @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 
    */ 
    public static class PlanetFragment extends Fragment { 
     public static final String ARG_PLANET_NUMBER = "planet_number"; 

     public PlanetFragment() { 
      // Empty constructor required for fragment subclasses 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_planet, container, false); 
      int i = getArguments().getInt(ARG_PLANET_NUMBER); 
      String planet = getResources().getStringArray(R.array.planets_array)[i]; 

      int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()), 
          "drawable", getActivity().getPackageName()); 
      ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId); 
      getActivity().setTitle(planet); 
      return rootView; 
     } 
    } 


} 

drawer_list_icon (XML) Я думаю, что Эрро здесь, но я не знаю, где.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/RelativeLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="48dp" 
    android:background="#F3F3F3" > 


    <TextView 
     android:id="@android:id/text1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:background="?android:attr/activatedBackgroundIndicator" 
     android:gravity="center_vertical" 
     android:minHeight="?android:attr/listPreferredItemHeightSmall" 
     android:paddingLeft="16dp" 
     android:paddingRight="16dp" 
     android:textAppearance="?android:attr/textAppearanceListItemSmall" 
     android:textColor="#FFFFFF" /> 
</RelativeLayout> 

<!-- 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/text1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceListItemSmall" 
    android:gravity="center_vertical" 
    android:paddingLeft="16dp" 
    android:paddingRight="16dp" 
    android:textColor="#fff" 
    android:background="?android:attr/activatedBackgroundIndicator" 
    android:minHeight="?android:attr/listPreferredItemHeightSmall"/> 
    --> 

LogCat

11-14 18:38:49.200: D/OpenGLRenderer(4973): Enabling debug mode 0 
11-14 18:38:49.210: E/ArrayAdapter(4973): You must supply a resource ID for a TextView 
11-14 18:38:49.210: D/AndroidRuntime(4973): Shutting down VM 
11-14 18:38:49.210: W/dalvikvm(4973): threadid=1: thread exiting with uncaught exception (group=0x64c97b20) 
11-14 18:38:49.210: D/BstCommandProcessor-Application(3198): Application crash has been observed. 
11-14 18:38:49.210: W/BstCommandProcessor-Application(3198): in sendHttpRequest, requestType is of CRASH_APP type but one of the requiredInfo is NULL, crashedApp = [email protected] 
11-14 18:38:49.210: D/BstCommandProcessor-Application(3198): in sendHttpRequest, request to send to (fqdn): http://10.0.2.2:2861/AppCrashedInfo 
11-14 18:38:49.210: D/BstCommandProcessor-Application(3198): data: {"packageName":"com.exemplo.myapp","shortPackageName":"com.exemplo.myapp","versionCode":1,"versionName":"1.0"} 
11-14 18:38:49.210: D/AndroidRuntime(4973): procName from cmdline: com.exemplo.myapp 
11-14 18:38:49.210: E/AndroidRuntime(4973): in writeCrashedAppName, pkgName :com.exemplo.myapp 
11-14 18:38:49.210: D/AndroidRuntime(4973): file written successfully with content: com.exemplo.myapp StringBuffer : ;com.exemplo.myapp 
11-14 18:38:49.220: I/Process(4973): Sending signal. PID: 4973 SIG: 9 
11-14 18:38:49.220: E/AndroidRuntime(4973): FATAL EXCEPTION: main 
11-14 18:38:49.220: E/AndroidRuntime(4973): Process: com.exemplo.myapp, PID: 4973 
11-14 18:38:49.220: E/AndroidRuntime(4973): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.AbsListView.obtainView(AbsListView.java:2263) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.ListView.makeAndAddView(ListView.java:1790) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.ListView.fillDown(ListView.java:691) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.ListView.fillFromTop(ListView.java:752) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.ListView.layoutChildren(ListView.java:1630) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.AbsListView.onLayout(AbsListView.java:2091) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.View.layout(View.java:14876) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewGroup.layout(ViewGroup.java:4631) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:714) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.View.layout(View.java:14876) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewGroup.layout(ViewGroup.java:4631) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.FrameLayout.onLayout(FrameLayout.java:388) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.View.layout(View.java:14876) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewGroup.layout(ViewGroup.java:4631) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:374) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.View.layout(View.java:14876) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewGroup.layout(ViewGroup.java:4631) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.FrameLayout.onLayout(FrameLayout.java:388) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.View.layout(View.java:14876) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewGroup.layout(ViewGroup.java:4631) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1994) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1751) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1007) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5677) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.Choreographer.doCallbacks(Choreographer.java:574) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.Choreographer.doFrame(Choreographer.java:544) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.os.Handler.handleCallback(Handler.java:733) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.os.Handler.dispatchMessage(Handler.java:95) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.os.Looper.loop(Looper.java:136) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.app.ActivityThread.main(ActivityThread.java:5021) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at java.lang.reflect.Method.invokeNative(Native Method) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at java.lang.reflect.Method.invoke(Method.java:515) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at dalvik.system.NativeStart.main(Native Method) 
11-14 18:38:49.220: E/AndroidRuntime(4973): Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView 
11-14 18:38:49.220: E/AndroidRuntime(4973):  at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:379) 
11-14 18:38:49.220: E/AndroidRuntime(4973):  ... 40 more 
11-14 18:38:49.230: I/ActivityManager(3006): Process com.exemplo.myapp (pid 4973) has died. 
+2

могли бы вы опубликовать LogCat? –

+0

Или лучше, чем стек логарифма. – rekire

ответ

1

ArrayAdapter конструктор вы используете предполагает компоновку, состоящую только из одного TextView. Чтобы использовать ваш макет, который также включает RelativeLayout, вам необходимо использовать constructor, который позволяет указать TextView, который будет использовать адаптер.

Вместо

mDrawerList.setAdapter(new ArrayAdapter<String>(this, 
    R.layout.drawer_list_icon, mPlanetTitles)); 

использования

mDrawerList.setAdapter(new ArrayAdapter<String>(this, 
    R.layout.drawer_list_icon, android.R.id.text1, mPlanetTitles)); 
+0

Perfect. Спасибо. Поэтому необходимо написать андроид до Р.И. Я узнаю больше об этом. :) – YMELO

+0

'android.R.id' относится к идентификаторам платформы, которые отображаются в xml как' @android: id/... 'Довольно часто вы определяете свои собственные идентификаторы, используя' @ + id/.. . в xml, и эти идентификаторы вы можете получить в java из вашего пакета 'R.id'. – Brucelet

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