【问题标题】:Android: How to use classes in a different fileAndroid:如何在不同的文件中使用类
【发布时间】:2012-03-19 09:25:29
【问题描述】:

我正在尝试为我的许多可重用方法创建一个处理程序类。我在连接单独的类文件时遇到问题。

谁能告诉我这个例子失败的地方或者需要做什么才能让它工作?

ClassExampleActivity.java: 包 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: 包 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>

调用 testmethod() 时,android 应用会崩溃。如果我将其注释掉,它将运行并将 System.out.printlin() 消息打印到 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

【问题讨论】:

  • 不要使用 myhandler mh = new myhandler();活动。
  • 在 OnCreate() 方法中初始化布局之前您不能使活动的实例您可能必须启动 Activity 覆盖 oncreate 方法通过 SetContentView() 设置其内容然后设置其视图的属性.
  • Nitin 我正在努力实施您的建议。

标签: android class external


【解决方案1】:
  1. 将名称 myhandler 更改为“MyHandler”,听起来不错..
  2. 目前情况下,您不需要在 MyHandler 中扩展 Activity 类。
  3. 您正在设置文本值两次,从 testmethod 中删除以下行,它们不需要它们..

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

    infotext.setText(innermessage); 

如果您遇到任何错误,请尝试更新您的问题....

编辑

   //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);


    }
}

这应该有效!

【讨论】:

  • 1) 我将 myhandler 更改为 MyHandler 2) 移除扩展 Activity 时应用程序完全失败。 3)需要“TextView infotext = (TextView) findViewByID(R.id.infotext)”这一行来指定文本的去向。 “infotext.setText(内部消息);”插入文本。这不是重复。
  • 编辑了答案,添加了一个适用于 GingerBird 的工作代码!如果不适合您,请添加错误消息(或 LogCat msg)...
  • 阿米特。你的代码和我的完全一样。我没有任何问题,您包含的“退货”声明也没有任何问题。我用它来表明正在访问该类。我的问题和疑问是如何在课堂上使用 TextView。这就是产生错误的原因。我正在尝试制作可重用的课程。我可以在 ClassExampleActivity.java 类中使用 TextView 功能。但是我不知道如何在 MyHandler.java 类中使用它而不会使应用程序崩溃。谢谢!
  • LogCat 输出附加到原始消息中。
  • @plz 查看编辑后的代码....我添加了一个 TextView 作为 testMethod() 的参考参数....希望可行!!!
【解决方案2】:

我在这里回答,所以你可以更好地看到我的解释。

在 MyHandler 类中,您执行以下操作:

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

您可以在 Android 参考中看到:

公共视图 findViewById (int id)

自:API 级别 1 从在 onCreate(Bundle) 中处理的 XML 中查找由 id 属性标识的视图。 如果找到则返回视图,否则返回 null。

据我所知,您没有在 MyHandler 类中处理任何 XML,因此您不能从 XML 中获取 TextView 并且它始终为空。

希望对你有帮助。

【讨论】:

  • 我确定您的方向是正确的。我认为视图定义是继承的。请原谅我如此回应,但我一直在尝试找出如何将此视图定义添加到 MyHandler 类。我正在尝试组织我在这方面的各种尝试,并找出一个向你展示的好方法。我会尽快发布示例。
【解决方案3】:

你检查过 infotext 是否为 NULL 吗?

【讨论】:

  • classexampleactivity.java 文件中使用了用于访问信息文本的相同行(语法)。 infotext 使用 infotext.setText() 方法设置。如果它为空,我该怎么做才能让它停止崩溃并实际加载它给出的内部消息字符串参数?
  • Gutiory。查看我附加到原始消息的 LogCat 似乎存在一些关于 null 的问题:03-20 17:03:42.853: E/AndroidRuntime(654): Caused by: java.lang.NullPointerException 你知道为什么有 NullPointerException 吗?如您所见,“innermessage”不是空字符串。你可以说出来,因为它实际上可以将字符串返回给主类。 infotext接收的类型是否设置为:TextView infotext = (TextView) findViewById(R.id.infotext);
【解决方案4】:

您是否记得将这两个活动都添加到您的 AndroidManifest.xml 中? 不止一两次,这让我感到困惑。

【讨论】:

  • 我不记得也不知道将条目放入 AndroidManifest.xml 文件中。我研究了如何放置条目。这没有帮助。我会将 AndrodManifest.xml 文件添加到上面原始问题的代码中。
【解决方案5】:

我可以在 Android 中使用类 ..

因为你..

非常感谢您的帮助。

评论1:

您应该将 .. myhandler .. 替换为 .. MyHandler

评论2:

你应该复制过去..块..(来自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>

并将“.ClassExampleActivity”替换为“.MyHandler”

得到

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

评论 3

ClassExampleActivity.java .. 和 ..Myhandler.java

必须在..同一个文件夹中..

(classexample .. 来自文件夹 .. apolo .. 来自文件夹 .. com)

您可以将 .. ".MyHandler" .. 替换为 "com.apollo.classexample.MyHandler"

评论 4 我的文件

MyHandler.java .. 和 .. MainActivity.java

都是 .. 在文件夹 .. iceplanets .. 来自文件夹 .. pak

评论 5 我的文件的内容..

MyHandler.java .. 在下面

包装 pak.iceplanets;

导入android.app.Activity;

导入android.widget.TextView;

公共类 MyHandler 扩展 Activity {

public void testMethod(TextView txtView){

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

    txtView.setText(innerMessage); 
}

}

评论 6

因为我用的是 Eclipse

我自动..在文件夹..activity_main.xml中写入..

我得到了线条

<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" />

注释 7 使用(类)MyHandler

我写了(..在 MainActivity.java 中)

线条..

我的处理程序 mh;

TextView infoText;

行后

公共类 MainActivity 扩展 Activity {

...

我还写了(.. in onCreate(Bundle savedInstanceState){)

线条

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

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

 MyHandler mh = new MyHandler();

 mh.testMethod(infoText);

在 .. 行之后 .. setContentView(R.layout.activity_main);

.....

我的代码片段..我在上面写的..

在我的电脑上运行良好。

成功

最好的问候,托尼奥

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多