Monday, November 21, 2011

java.lang.ClassCastException: android.widget.Button problem

 

 

While trying to create a clickable ImageView, I received this error:

 

11-21 15:35:15.940: E/AndroidRuntime(7607): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mctexpert.android.ishunt/com.mctexpert.android.ishunt.MenuScreen}: java.lang.ClassCastException: android.widget.Button

 

The problem was it thought that I was trying to work with a button as opposed to the image.  I ended up deleting the ImageView from the layout and then recreating it.  That took care of this problem.

Thursday, November 10, 2011

Lock a screen in portrait mode without losing data

 

As I continue to progress in my Android education, I’m finding out how to make my apps work the way I want them to do.  In this case, I needed to prevent the screen from rotating.  I also forgot that Android calls the onCreatemethod every time you do this.  Here is how I fixed that,

 

I opened the AndroidManifest.xml file.  I added two lines of code:

android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">

The first tells Android to keep the screen in portrait mode. 

The second tells Android that in the event the device is rotated or the keyboard is pulled out, do not execute the onCreate method.  Instead, keep going with what you currently have open. 

Below is how the code in my AndroidManifest XML file looks.  Notice that these elements are called on a per activity bases.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="
http://schemas.android.com/apk/res/android"
    package="com.mctexpert.android.orientation"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".OrientationActivity"
            android:screenOrientation="portrait"
            android:configChanges="keyboardHidden|orientation">
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Wednesday, November 2, 2011

Generate a random number on Android

For this I have a TextView named mTextField3

 

Random r = new Random();

int i1=r.nextInt(100);

mTextView3.setText(String.valueOf(i1));

 

This will generate a random number between 0 and 99.