Android: How to use classes in a different file

家住魔仙堡 提交于 2019-12-12 16:14:04

问题


I'm trying to make a handler class for many of my reusable methods. I'm having problems interfacing the separate class file.

Can someone tell me what this example fails or what would have to be done to make it work?

ClassExampleActivity.java: package com.apollo.classexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;


public class ClassExampleActivity extends Activity {
    /** Called when the activity is first created. */

    TextView infotext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        String infostring = "Main Activity Class\n";

        Myhandler mh = new Myhandler();
        infostring += mh.testmethod();

        // Trying to use the TextView widget from this MyHandler class
        // This works from the main class but fails in the MyHandler class
        TextView infotext = (TextView) findViewById(R.id.infotext);
        infotext.setText(infostring);
    }
}

Myhandler.java: package com.apollo.classexample;

import android.widget.TextView;
import android.app.Activity;

public class Myhandler extends Activity {

    public String testmethod(){
        String innermessage = "This is a message from the innerclass\n";
        System.out.println(innermessage);

            /* This is an important component that I would like to use in this class
             Commenting these lines out and the application doesn't crash.
             I'm trying to learn how to use the next two lines in this MyHandler 
             class which I'm trying to make portable and reusable for other
             projectes.
            */
        TextView infotext = (TextView) findViewById(R.id.infotext);
            infotext.setText(innermessage); 

            // Placed to show that the MyHandler class is actually accessed
        return innermessage;
    }

}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.apollo.classexample"
    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:name=".ClassExampleActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

    </application>

</manifest>

When calling the testmethod() the android app will crash. If I comment it out it'll run and print the System.out.printlin() message to the LogCat.

LogCat:

03-20 17:03:42.783: I/System.out(654): This is a message from the innerclass
03-20 17:03:42.783: D/AndroidRuntime(654): Shutting down VM
03-20 17:03:42.803: W/dalvikvm(654): threadid=1: thread exiting with uncaught exception (group=0x40014760)
03-20 17:03:42.853: E/AndroidRuntime(654): FATAL EXCEPTION: main
03-20 17:03:42.853: E/AndroidRuntime(654): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apollo.classexample/com.apollo.classexample.ClassExampleActivity}: java.lang.NullPointerException
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1748)
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.app.ActivityThread.access$1500(ActivityThread.java:122)
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.os.Looper.loop(Looper.java:132)
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.app.ActivityThread.main(ActivityThread.java:4025)
03-20 17:03:42.853: E/AndroidRuntime(654):  at java.lang.reflect.Method.invokeNative(Native Method)
03-20 17:03:42.853: E/AndroidRuntime(654):  at java.lang.reflect.Method.invoke(Method.java:491)
03-20 17:03:42.853: E/AndroidRuntime(654):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
03-20 17:03:42.853: E/AndroidRuntime(654):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
03-20 17:03:42.853: E/AndroidRuntime(654):  at dalvik.system.NativeStart.main(Native Method)
03-20 17:03:42.853: E/AndroidRuntime(654): Caused by: java.lang.NullPointerException
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.app.Activity.findViewById(Activity.java:1744)
03-20 17:03:42.853: E/AndroidRuntime(654):  at com.apollo.classexample.MyHandler.testmethod(MyHandler.java:16)
03-20 17:03:42.853: E/AndroidRuntime(654):  at com.apollo.classexample.ClassExampleActivity.onCreate(ClassExampleActivity.java:23)
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
03-20 17:03:42.853: E/AndroidRuntime(654):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
03-20 17:03:42.853: E/AndroidRuntime(654):  ... 11 more

回答1:


  1. Change the name myhandler to 'MyHandler', that sounds nice..
  2. In present situation you dont need to extend Activity class in MyHandler.
  3. You are setting text value twice delete following lines from testmethod they are not needed their..

TextView infotext = (TextView) findViewById(R.id.infotext);

    infotext.setText(innermessage); 

try and update your question if you get any error....

EDIT

   //MyHandler.java
   public class Myhandler {

        public void testMethod(TextView txtView){
            String innermessage = "This is a message from the innerclass.";            
            txtView.setText(innerMessage); 

        }

    }

// ClassExampleActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ClassExampleActivity extends Activity {


    TextView infotext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        String infostring = "Main Activity Class\n";
        TextView infotext = (TextView) findViewById(R.id.infotext);
        infotext.setText(infostring);

        Myhandler mh = new Myhandler();
        mh.testMethod(infoText);


    }
}

This should work!!




回答2:


I answer here, so you can see better my explanation.

In MyHandler class, you do the follow:

TextView infotext = (TextView) findViewById(R.id.infotext);

As you can see in the Android Reference:

public View findViewById (int id)

Since: API Level 1 Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle). Returns The view if found or null otherwise.

As I can understand there you haven't process any XML in MyHandler class, so you can't take the TextView from the XML and It is always null.

I hope that helps.




回答3:


Have you check if infotext is NULL?.




回答4:


Have you remembered to add both activities to your AndroidManifest.xml? That's caught me out on more than one or two occasions.




回答5:


I am able to work with classes .. in Android

because of you ..

Thank you very much for your help.

Comment 1:

You should replace .. myhandler .. with .. MyHandler

Comment 2:

You should copy-past .. the block .. (from AndroidManifest.xml)

    <activity
        android:name=".ClassExampleActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

and replace ".ClassExampleActivity" with ".MyHandler"

to get

    <activity
        android:name="pak.iceplanets.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <activity
        android:name="pak.iceplanets.MyHandler"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

Comment 3

ClassExampleActivity.java .. and .. Myhandler.java

must be in .. the same folder ..

(classexample .. from the folder .. apolo .. from the folder .. com)

You may replace .. ".MyHandler" .. with "com.apollo.classexample.MyHandler"

Comment 4 My files

MyHandler.java .. and .. MainActivity.java

are both .. in the folder .. iceplanets .. from the folder .. pak

Comment 5 The content .. of my file

MyHandler.java .. is below

package pak.iceplanets;

import android.app.Activity;

import android.widget.TextView;

public class MyHandler extends Activity {

public void testMethod(TextView txtView){

    String innerMessage = "This is a message from the innerclass.";            

    txtView.setText(innerMessage); 
}

}

Comment 6

Because I use Eclipse

I automatically .. write .. in the folder .. activity_main.xml

I obtained the lines

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"

    android:layout_centerHorizontal="true"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

Comment 7 To use (the class) MyHandler

I wrote (.. in MainActivity.java)

the lines ..

MyHandler mh;

TextView infoText;

after the line

public class MainActivity extends Activity {

...

I also wrote ( .. in onCreate(Bundle savedInstanceState){ )

the lines

 // infoText .. is a reference to .. textView1       

 TextView infoText = (TextView) findViewById(R.id.textView1);      

 MyHandler mh = new MyHandler();

 mh.testMethod(infoText);

after .. the line .. setContentView(R.layout.activity_main);

.....

My pieces of the code .. I wrote above ..

works well .. on my computer.

Success

Best regards, Tonio



来源:https://stackoverflow.com/questions/9767657/android-how-to-use-classes-in-a-different-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!