按下按钮时应用程序崩溃

时间:2015-05-15 02:24:44

标签: android android-actionbar

我几天都在努力寻找解决方案,这让我感到疯狂。我目前正在关注http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems

中的教程

不幸的是,当按下SEND按钮时应用程序崩溃(在执行操作栏之前工作正常)

以下是涉及的文件:

1. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.myfirstapps" >
    <uses-sdk android:minSdkVersion="7"
    android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat.Light.DarkActionBar">

        <!-- parent activity-->
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <!--second activity -->
        <activity
            android:name=".DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName=".MyActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MyActivity" />
        </activity>


    </application>

</manifest>
​
  1. MyActivity.java
  2. package com.mycompany.myfirstapps;
    
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.support.v7.app.AppCompatActivity;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.content.Intent;
    import android.widget.EditText;
    
    
    public class MyActivity extends AppCompatActivity {
        public final static String EXTRA_MESSAGE="com.mycompany.myfirstapps.MESSAGE";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            // If your minSdkVersion is 11 or higher, instead use:
            //getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu items for use in the action bar
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.main_activity_actions, menu);
            return super.onCreateOptionsMenu(menu);
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle presses on the action bar items
            switch (item.getItemId()) {
                case R.id.action_search:
                    openSearch();
                    return true;
                case R.id.action_settings:
                    openSettings();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    
        //called when user click the button
        public void sendMessage(View view){
            Intent intent = new Intent(this,DisplayMessageActivity.class);
            EditText editText=(EditText)findViewById(R.id.edit_message);
            String message=editText.getText().toString();
            intent.putExtra(EXTRA_MESSAGE,message);
            startActivity(intent);
        }
    
    
        private void openSearch() {
         //do something
        }
    
    
        private void openSettings() {
    //do something
        }
    
    }
    ​
    
    1. DisplayMessageActivity.java
    2. package com.mycompany.myfirstapps;
      
      import android.content.Intent;
      import android.os.Bundle;
      import android.support.v7.app.AppCompatActivity;
      import android.view.Menu;
      import android.view.MenuItem;
      import android.widget.TextView;
      
      
          public class DisplayMessageActivity extends AppCompatActivity {
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              Intent intent= getIntent();
      
              //create the text view
              String message=intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
              TextView textview= new TextView(this);
              textview.setTextSize(40);
              textview.setText(message);
      
              //set the text view as the activity layout
              setContentView(textview);
          }
      
          @Override
          public boolean onCreateOptionsMenu(Menu menu) {
              // Inflate the menu; this adds items to the action bar if it is present.
              getMenuInflater().inflate(R.menu.menu_display_message, 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) {
                  return true;
              }
      
              return super.onOptionsItemSelected(item);
          }
      }
      
      1. activity_main.xml中
      2. <LinearLayout 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:orientation="horizontal"
        android:theme="@style/CustomActionBarTheme">
        
        <EditText
            android:id="@+id/edit_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="@string/edit_message"/>
        
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_send"
            android:onClick="sendMessage"/>
        
        </LinearLayout>
        
        1. 的build.gradle
        2. apply plugin: 'com.android.application'
          
          android {
              compileSdkVersion 22
              buildToolsVersion "22.0.1"
          
              defaultConfig {
                  applicationId "com.mycompany.myfirstapps"
                  minSdkVersion 8
                  targetSdkVersion 22
                  versionCode 1
                  versionName "1.0"
              }
              buildTypes {
                  release {
                      minifyEnabled false
                      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                  }
              }
          }
          
          dependencies {
              compile fileTree(dir: 'libs', include: ['*.jar'])
              compile 'com.android.support:appcompat-v7:22.1.1'
          }
          ​
          

          logcat的

          05-14 22:57:03.139    2514-2562/android.process.acore I/ContactLocale﹕ AddressBook Labels [en-US]: [, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Α, Β, Γ, Δ, Ε, Ζ, Η, Θ, Ι, Κ, Λ, Μ, Ν, Ξ, Ο, Π, Ρ, Σ, Τ, Υ, Φ, Χ, Ψ, Ω, , А, Б, В, Г, Д, Ђ, Е, Є, Ж, З, И, І, Ї, Й, Ј, К, Л, Љ, М, Н, Њ, О, П, Р, С, Т, Ћ, У, Ф, Х, Ц, Ч, Џ, Ш, Щ, Ю, Я, , א, ב, ג, ד, ה, ו, ז, ח, ט, י, כ, ל, מ, נ, ס, ע, פ, צ, ק, ר, ש, ת, , ا, ب, ت, ث, ج, ح, خ, د, ذ, ر, ز, س, ش, ص, ض, ط, ظ, ع, غ, ف, ق, ك, ل, م, ن, ه, و, ي, , ก, ข, ฃ, ค, ฅ, ฆ, ง, จ, ฉ, ช, ซ, ฌ, ญ, ฎ, ฏ, ฐ, ฑ, ฒ, ณ, ด, ต, ถ, ท, ธ, น, บ, ป, ผ, ฝ, พ, ฟ, ภ, ม, ย, ร, ฤ, ล, ฦ, ว, ศ, ษ, ส, ห, ฬ, อ, ฮ, , ㄱ, ㄴ, ㄷ, ㄹ, ㅁ, ㅂ, ㅅ, ㅇ, ㅈ, ㅊ, ㅋ, ㅌ, ㅍ, ㅎ, , あ, か, さ, た, な, は, ま, や, ら, わ, #, ]
          05-14 22:57:05.181    2514-2532/android.process.acore V/BackupServiceBinder﹕ doBackup() invoked
          05-14 22:57:05.508    2514-2532/android.process.acore I/art﹕ WaitForGcToComplete blocked for 267.334ms for cause DisableMovingGc
          05-14 22:57:05.619    2514-2532/android.process.acore E/DictionaryBackupAgent﹕ Couldn't read from the cursor
          05-14 22:57:05.722    2514-2562/android.process.acore I/art﹕ WaitForGcToComplete blocked for 357.236ms for cause DisableMovingGc
          05-15 01:35:32.770    2514-2525/android.process.acore W/art﹕ Suspending all threads took: 57.246ms
          05-15 01:35:35.813    2514-2527/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
              java.lang.Throwable: Explicit termination method 'close' not called
                      at dalvik.system.CloseGuard.open(CloseGuard.java:184)
                      at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
                      at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
                      at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
                      at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
                      at android.os.Binder.execTransact(Binder.java:446)
          05-15 01:35:35.925    2514-2527/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
              java.lang.Throwable: Explicit termination method 'close' not called
                      at dalvik.system.CloseGuard.open(CloseGuard.java:184)
                      at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
                      at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
                      at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
                      at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:64)
                      at android.os.Binder.execTransact(Binder.java:446)
          05-15 01:35:36.578    2514-2527/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
              java.lang.Throwable: Explicit termination method 'close' not called
                      at dalvik.system.CloseGuard.open(CloseGuard.java:184)
                      at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
                      at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
                      at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
                      at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:71)
                      at android.os.Binder.execTransact(Binder.java:446)
          ​
          

          可能有什么不对?

2 个答案:

答案 0 :(得分:2)

将您的EditText移动到MyActivity.java中的onCreate()方法

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

    EditText editText=(EditText)findViewById(R.id.edit_message);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    // If your minSdkVersion is 11 or higher, instead use:
    //getActionBar().setDisplayHomeAsUpEnabled(true);
}

在sendMessage()方法中,只需删除该行。

编辑:您似乎正在从新的AppCompatActivity扩展。尝试在两个活动中将其更改为ActionBarActivity。例如:

public class MyActivity extends ActionBarActivity {...}
public class DisplayMessageActivity extends ActionBarActivity {...}

编辑:如果你计划不使用ActionBarActivity,那么你需要定义一个自定义工具栏并像这样初始化它。

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

答案 1 :(得分:0)

最后,我设法在挣扎了近3天后获得解决方案。解决这个问题的过程对我来说真的是一个旅程,作为Android的新手。 这是在此过程中跟踪和解决的错误和警告列表:

  1. 班级名称ActionBarActivity被删除了 公共类MyActivity扩展了ActionBarActivity 解释是: 从版本22.1.0开始,不推荐使用ActionBarActivity类。您应该使用AppCompatActivity
  2. 一旦我清除了所有弃用的问题,就会出现下一个错误:

    1. 显示java.lang.NullPointerException 我通过检查空值

      解决了这个问题(或者至少我是这么认为的)

      断言getSupportActionBar()!= null; getSupportActionBar()setDisplayHomeAsUpEnabled(真);

    2. 下一个错误总是指向sendMessage(View视图) 我发现这篇文章: java.lang.IllegalStateExeception: could not find method in activity class

    3. 它解决了我的问题。我的实际错误是我在AndroidManifest.xml中设置了主题,并再次将它们设置在布局文件中。导致应用程序崩溃。我删除了layout.xml文件中的那个。