在android中调用自定义类/方法

时间:2014-06-18 05:32:46

标签: java android xml eclipse parsing

我是一名新的Android开发人员,这是我的第一个问题,所以请耐心等待......

我正在尝试在我创建的类中调用自定义方法,但是在控制台中出现以下错误:

Logcat:

06-18 06:57:13.291: D/AndroidRuntime(1251): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
06-18 06:57:13.291: D/AndroidRuntime(1251): CheckJNI is ON
06-18 06:57:13.331: D/dalvikvm(1251): Trying to load lib libjavacore.so 0x0
06-18 06:57:13.341: D/dalvikvm(1251): Added shared lib libjavacore.so 0x0
06-18 06:57:13.371: D/dalvikvm(1251): Trying to load lib libnativehelper.so 0x0
06-18 06:57:13.371: D/dalvikvm(1251): Added shared lib libnativehelper.so 0x0
06-18 06:57:14.061: D/AndroidRuntime(1251): Calling main entry com.android.commands.pm.Pm
06-18 06:57:14.091: D/AndroidRuntime(1251): Shutting down VM
06-18 06:57:14.101: D/dalvikvm(1251): GC_CONCURRENT freed 94K, 18% free 469K/568K, paused 0ms+1ms, total 12ms
06-18 06:57:14.101: D/dalvikvm(1251): Debugger has detached; object registry had 1 entries
06-18 06:57:14.621: D/AndroidRuntime(1263): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
06-18 06:57:14.621: D/AndroidRuntime(1263): CheckJNI is ON
06-18 06:57:14.661: D/dalvikvm(1263): Trying to load lib libjavacore.so 0x0
06-18 06:57:14.671: D/dalvikvm(1263): Added shared lib libjavacore.so 0x0
06-18 06:57:14.701: D/dalvikvm(1263): Trying to load lib libnativehelper.so 0x0
06-18 06:57:14.701: D/dalvikvm(1263): Added shared lib libnativehelper.so 0x0
06-18 06:57:15.411: D/AndroidRuntime(1263): Calling main entry com.android.commands.am.Am
06-18 06:57:15.421: D/dalvikvm(1263): Note: class Landroid/app/ActivityManagerNative; has 157 unimplemented (abstract) methods
06-18 06:57:15.452: I/ActivityManager(274): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.virginmobileinfo/.MainActivity} from pid 1263
06-18 06:57:15.502: D/AndroidRuntime(1263): Shutting down VM
06-18 06:57:15.522: D/dalvikvm(1263): GC_CONCURRENT freed 95K, 17% free 499K/596K, paused 1ms+1ms, total 11ms
06-18 06:57:15.522: D/jdwp(1263): Got wake-up signal, bailing out of select
06-18 06:57:15.522: D/dalvikvm(1263): Debugger has detached; object registry had 1 entries
06-18 06:57:15.661: E/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property
06-18 06:57:16.791: I/Process(1232): Sending signal. PID: 1232 SIG: 9
06-18 06:57:16.812: I/ActivityManager(274): Process com.example.virginmobileinfo (pid 1232) has died.
06-18 06:57:16.831: D/dalvikvm(1273): Not late-enabling CheckJNI (already on)
06-18 06:57:16.852: I/ActivityManager(274): Start proc com.example.virginmobileinfo for activity com.example.virginmobileinfo/.MainActivity: pid=1273 uid=10049 gids={50049, 1028}
06-18 06:57:17.341: E/Trace(1273): error opening trace file: No such file or directory (2)
06-18 06:57:17.651: D/dalvikvm(1273): GC_FOR_ALLOC freed 96K, 8% free 2566K/2784K, paused 32ms, total 35ms
06-18 06:57:17.661: I/dalvikvm-heap(1273): Grow heap (frag case) to 3.227MB for 635812-byte allocation
06-18 06:57:17.721: D/dalvikvm(1273): GC_FOR_ALLOC freed 2K, 7% free 3185K/3408K, paused 60ms, total 60ms
06-18 06:57:17.761: D/dalvikvm(1273): GC_CONCURRENT freed <1K, 7% free 3186K/3408K, paused 4ms+2ms, total 41ms
06-18 06:57:17.831: D/AndroidRuntime(1273): Shutting down VM
06-18 06:57:17.831: W/dalvikvm(1273): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-18 06:57:17.851: E/AndroidRuntime(1273): FATAL EXCEPTION: main
06-18 06:57:17.851: E/AndroidRuntime(1273): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.virginmobileinfo/com.example.virginmobileinfo.MainActivity}: android.os.NetworkOnMainThreadException
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.os.Looper.loop(Looper.java:137)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at java.lang.reflect.Method.invokeNative(Native Method)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at java.lang.reflect.Method.invoke(Method.java:511)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at dalvik.system.NativeStart.main(Native Method)
06-18 06:57:17.851: E/AndroidRuntime(1273): Caused by: android.os.NetworkOnMainThreadException
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:439)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:424)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:178)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at org.jsoup.helper.HttpConnection.post(HttpConnection.java:173)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at com.example.virginmobileinfo.minuteschecker.UserData.DownloadUserProfile(UserData.java:31)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at com.example.virginmobileinfo.minuteschecker.UserData.LoadData(UserData.java:46)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at com.example.virginmobileinfo.MainActivity.onCreate(MainActivity.java:110)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.app.Activity.performCreate(Activity.java:5104)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-18 06:57:17.851: E/AndroidRuntime(1273):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-18 06:57:17.851: E/AndroidRuntime(1273):     ... 11 more
06-18 06:57:17.881: W/ActivityManager(274):   Force finishing activity com.example.virginmobileinfo/.MainActivity
06-18 06:57:18.051: D/dalvikvm(274): GC_FOR_ALLOC freed 661K, 24% free 7194K/9380K, paused 124ms, total 133ms
06-18 06:57:18.221: E/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property
06-18 06:57:18.582: W/ActivityManager(274): Activity pause timeout for ActivityRecord{40f99c98 u0 com.example.virginmobileinfo/.MainActivity}
06-18 06:57:18.651: E/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property
06-18 06:57:18.681: W/EGL_emulation(398): eglSurfaceAttrib not implemented
06-18 06:57:20.464: D/ExchangeService(633): Received deviceId from Email app: null
06-18 06:57:20.464: D/ExchangeService(633): !!! deviceId unknown; stopping self and retrying

这是我的班级:

package com.example.virginmobileinfo.minuteschecker;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Scanner;

import org.jsoup.Jsoup;

public class UserData {

    private org.jsoup.nodes.Document vm_website_data;
    private String[] tags_to_load = {"first-name", "phone-number", "balance", "total", "start-date", "mins-used", "mins-left"};
    private String user_data_file_path = "user_data.txt";
    private String data_to_sort;

    /** Download latest profile source code */
    public String DownloadUserProfile(){
        //showDebugToast("Attempting to download profile...");
        vm_website_data = null; //declare variable
        try {
            //showDebugToast("Downloading profile...");
            vm_website_data = Jsoup.connect("https://www2.virginmobileusa.com/login/login.do")
                    .timeout(10*6000)
                    .data("min", "5555555555")
                    .data("vkey", "999999")
                    .data("submit", "submit")
                    .post();
            //showDebugToast("Profile downloaded!");
        } catch (IOException e) {
            e.printStackTrace(); //Return blank if can't download profile
        }
        //showDebugToast(vm_website_data.toString());
        return vm_website_data.toString(); //Return data if successful
    }


    /** Filter for usable data from VM website code */
    public void LoadData(){

        File file = new File(user_data_file_path);
        if(file.exists() == false){
            data_to_sort = DownloadUserProfile();
            data_to_sort = StringUtils.substringBetween(data_to_sort, "<vmu-page", "</vmu-page>");
        } else if(data_to_sort == null){
            try {
                data_to_sort = new Scanner(file).useDelimiter("\\A").next();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        //showDebugToast("Running filter...");

        /* Turn bulk info into pieces */
        String[] output_arr = new String[tags_to_load.length];
        for (int i = 0; i < tags_to_load.length; i++){
            String tag_id = tags_to_load[i];
            String tag_contents = StringUtils.substringBetween(data_to_sort, "<" + tags_to_load[i] + ">", "</" + tag_id + ">");
            output_arr[i] = "<" + tag_id + ">" + tag_contents + "</" + tag_id + ">";
            //showDebugToast(tag_id + " : " + tag_contents);
        }

        /* Save file if it didn't exist in the first place */
        if(file.exists() == false){
            saveUserProfile(output_arr);
        }
    }

    public void saveUserProfile(String[] output_arr){
        //showDebugToast("Saving profile...");
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(user_data_file_path, "UTF-8");
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        writer.println(Arrays.toString(output_arr));
        writer.close();

        //showDebugToast("Profile saved!");
    }

    public void showDebugToast(String messageText){
        //Toast.makeText(getApplicationContext(), messageText, Toast.LENGTH_SHORT).show();
        //System.out.println(messageText);
    }

}

编辑:最初的问题是UserData类处于启动配置中。我把它拿出来并在MainActivity活动中从OnCreate()调用方法LoadData()。

1 个答案:

答案 0 :(得分:0)

Android的入口点不像常规Java应用程序那样public static void main(String[] args),而是使用活动。

您应该将代码放在onCreate()onCreateView()onStart()或其他适用方法的活动(或片段)中。

阅读Activityits lifecycle(以及Fragment lifecycle),了解在何时选择执行代码的位置和时间。

编辑:Android中可能有一个带有main方法的类,但需要做一些配置,几乎肯定不是你想要做的。如果您有兴趣,请参阅以下主题related Question and Answerand another)。

编辑2:第二期

您的堆栈跟踪显示:

Caused by: android.os.NetworkOnMainThreadException
    ...
    at com.example.virginmobileinfo.minuteschecker.UserData.DownloadUserProfile(UserData.java:31)

您正在尝试在Android线程上进行网络互动,Android不允许这样做,因为它会使您的应用在通话期间无响应。

您需要查看AsyncTask或其他后台线程处理。有关主题are here

的Android文档