0

I have struggled to find the solution for couple of days and it has drive me nuts. I am currently following the tutorial in http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems

Unfortunately the application crashes when SEND button was pressed (It was working fine before the action bar was implemented)

Here are the involved files:

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

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

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

<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

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)
​

What could be wrong?

2 Answers2

2

Move your EditText inside of your onCreate() method in MyActivity.java

@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);
}

And inside your sendMessage() method, just remove that line.

Edit: It seems like you're extending from the new AppCompatActivity. Try changing it to ActionBarActivity in both the activities. For example:

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

Edit: If you're planning on not using the ActionBarActivity, then you need to define a custom Toolbar and initialze it like this..

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bidhan
  • 10,607
  • 3
  • 39
  • 50
  • I have tried but it doesnt work.Maybe i do it wrongly. please help me to understand the rationale of switching the code? what code should in the sendMessage()? – Noraida Arifin May 15 '15 at 03:56
  • Thank you but it still did not work. Since the version 22.1.0, the class ActionBarActivity is deprecated , that is why I am using public class DisplayMessageActivity extends AppCompatActivity – Noraida Arifin May 15 '15 at 05:18
  • You need to define a custom Toolbar before you can use getSupportActionBar(). See my edit. – Bidhan May 15 '15 at 05:43
0

Finally I manage to get the solution after struggling for almost 3 days. the process to resolve this issue is really a journey for me as a newbie in android. This is list of errors and warning tracked and solved during the process:

  1. The class name ActionBarActivity was strikeout in public class MyActivity extends ActionBarActivity The explanation is: Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity

once I clear all the deprecated issue , the next error:

  1. java.lang.NullPointerException I solved this issue ( or at least I thought so) by checking the null value

    assert getSupportActionBar() != null; getSupportActionBar().setDisplayHomeAsUpEnabled(true);

  2. Next error was always pointing to the sendMessage(View view) I found this post : java.lang.IllegalStateExeception: could not find method in activity class

And it solved my problem. My actual mistake was I have set the theme in AndroidManifest.xml and again i set the them in layout file. Causing the application to crash. I removed the one in layout.xml file.

Community
  • 1
  • 1