Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App (retired 2014) Pretty Little Things Customizing Buttons and Labels

Benjamin Williams
Benjamin Williams
488 Points

Centering TextView1 Crashes Crystall.Ball

Hi There,

I am not sure where I have gone wrong I have gone over this part of the tutorial about 10 times, I can move the Button to the bottom of the screen, change its colour, font size etc. The App runs fine.

I can change the colour of the TextView to white and the font size and the app still runs fine, but as soon as I move it to centre of the app:

Unfortunately, Crystal Ball has stopped.

 <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:background="@android:color/black"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.crystalball.MainActivity$PlaceholderFragment" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter"
        android:src="@drawable/ball01" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="Enlighten Me"
        android:textColor="#3f0f7f"
        android:textSize="24sp"
        android:textStyle="italic|bold"
        android:typeface="serif" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="169dp"
        android:gravity="center_horizontal"
        android:text="teststst"
        android:textColor="#ffffff"
        android:textSize="32sp" />

</RelativeLayout>

7 Answers

Benjamin Williams
Benjamin Williams
488 Points

No worries

package com.example.crystalball;

import java.util.Random;

public class CrystalBall {

    // Member variable (properties about the object)

    public String[] mAnswers = {
            "It is certain",
            "It is difficult to say",
            "It is most definetly yes",
            "All signs point to yes",
            "The stars are not aligned",
            "It is doubtful",
            "Ask me again later",
            "It is hard to say",
            "Concentrate and ask again",
            "I am not a liberty to answer",
            "Please come again"     
    };

    // Methods (abilities things the object can do)

    public String getAnAnswer() {



        String answer = "";

        // Randomly answer yes, no or maybe

        Random randomGenerator = new Random(); //Construct a new random number generator
        int randomNumber = randomGenerator.nextInt(mAnswers.length); 

        answer = mAnswers[randomNumber];

        return answer;
    }
}

Ok before I go to bed change MainActivity to extend Activity.. Then organize your imports and you should get the following

<p>
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
</p>

That runs without crashing for me

What error messages are you getting in log cat?

I only ask because when I load your exact xml into my project it still runs and does not crash can you copy and paste the log cat errors for me? Please

Benjamin Williams
Benjamin Williams
488 Points

Hi Tom,

Please see error messages below (great surname by the way!)

05-27 01:33:15.418: D/dalvikvm(1034): Not late-enabling CheckJNI (already on)
05-27 01:33:18.058: D/dalvikvm(1034): GC_FOR_ALLOC freed 91K, 6% free 2923K/3084K, paused 184ms, total 206ms
05-27 01:33:18.058: I/dalvikvm-heap(1034): Grow heap (frag case) to 3.691MB for 811216-byte allocation
05-27 01:33:18.478: D/dalvikvm(1034): GC_FOR_ALLOC freed <1K, 5% free 3715K/3880K, paused 365ms, total 365ms
05-27 01:33:18.538: D/AndroidRuntime(1034): Shutting down VM
05-27 01:33:18.538: W/dalvikvm(1034): threadid=1: thread exiting with uncaught exception (group=0xb1adeba8)
05-27 01:33:18.558: E/AndroidRuntime(1034): FATAL EXCEPTION: main
05-27 01:33:18.558: E/AndroidRuntime(1034): Process: com.example.crystalball, PID: 1034
05-27 01:33:18.558: E/AndroidRuntime(1034): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.crystalball/com.example.crystalball.MainActivity}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.os.Looper.loop(Looper.java:136)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.app.ActivityThread.main(ActivityThread.java:5017)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at java.lang.reflect.Method.invokeNative(Native Method)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at java.lang.reflect.Method.invoke(Method.java:515)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at dalvik.system.NativeStart.main(Native Method)
05-27 01:33:18.558: E/AndroidRuntime(1034): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
05-27 01:33:18.558: E/AndroidRuntime(1034):     at com.example.crystalball.MainActivity.onCreate(MainActivity.java:22)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.app.Activity.performCreate(Activity.java:5231)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-27 01:33:18.558: E/AndroidRuntime(1034):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-27 01:33:18.558: E/AndroidRuntime(1034):     ... 11 more

This looks to be an issue in the MainActivity.java file it looks like the way that it is being called it is trying to mutate the text view to a button which could be due to an invalid id call. Also I try not to use the graphical layout because I have had issues with what it generates on the back end. I think Ben would attest to that also it was one of the videos he ran into that. Anyway I am rambling now could you please post your code from the MainActivity class so I could view it. Thanks for the name comment I think your the first person to say anything about it.

Benjamin Williams
Benjamin Williams
488 Points

Here you go

package com.example.crystalball;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private CrystalBall mCrystalBall = new CrystalBall();

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

        // Declare our view variables 
        final TextView answerLabel = (TextView) findViewById(R.id.textView1);
        Button getAnswerButton = (Button) findViewById(R.id.button1);
        getAnswerButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String answer = mCrystalBall.getAnAnswer();


                // Update the label with our dynamic answer 
                answerLabel.setText(answer);

            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

Can you also give me your crystalBall class. Sorry I didn't ask before

Benjamin Williams
Benjamin Williams
488 Points

Thanks Tom, that did the trick.. how odd.. is this a known bug?

It's not really a "bug" per se. This really comes from Java and the languages interaction with android as a platform. Example Blood Orange = > Orange => Fruit, OR Blood Orange extends Orange and Orange extends Fruit. Extends is the Java terminology for class inheritance so in the above example Blood Orange is a grandchild of Fruit. Where it kinda got confusing for me at first is with android. Because the ActionBarActivity, Activity, etc. these although syntactically correct create a logic based error these classes that were extended have specific attributes or components needed directly related to the layout. Or they are not mutually exclusive to all layout types, again this is my understanding.

Another option is because ActionBarActivity is a member of the appcompat support library I have had times where Eclipse builds my workspace but everything is not synced and I have to restart Eclipse and let it sync everything.

Either of these two scenarios would have created your issue, but I am leaning towards the first.

Benjamin Williams
Benjamin Williams
488 Points

I changed it back to MainActivity and reset the imports and is working that way. Thanks again for all your help.

Benjamin Williams
Benjamin Williams
488 Points

Awesome thanks for that explanation Tom! Most insightful. Cheers.