CurrencyWidget应用程序运行时错误

时间:2011-11-25 11:53:17

标签: java android logcat runtimeexception

我是Android编程的新手,只是从http://www.droiddraw.org/tut4.html获取代码并尝试制作货币转换器应用程序。我打算从互联网上获取货币转换率并在应用程序中使用JSON。问题是我无法运行应用程序,我已经尝试了互联网上可用的所有可能的东西和解决方案来解决这个问题。清理项目,构建,刷新,重新导入等。请帮助我,并指出我错过了导致致命异常的任何内容,并且应用程序显示“CurrencyWidget意外停止”。 我在这里附上我的完整项目代码和LogCat错误,请帮助我。

CurrencyWidget.java

package com.kwantlen.android.currencywidget;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class CurrencyWidget extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // To prevent any ANR timeouts, we perform the update in a service
        context.startService(new Intent(context, UpdateService.class));
    }

    public static double getRate() {
        // In a real app, you might want to cache this object for performance.
        HttpClient http = new DefaultHttpClient();
        // In reality this would be a dynamic service.
        HttpGet get = new HttpGet("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=");

        double rate = 0.00;
        try {
            HttpResponse response = http.execute(get);
            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            response.getEntity().writeTo(outstream);
            outstream.flush();
            outstream.close();
            String data = new String(outstream.toByteArray(), "UTF-8");
            JSONObject obj = new JSONObject(new JSONTokener(data));
            rate = obj.getDouble("rate");
        } catch (IOException ex) {
            Log.e("CurrencyWidget", "IO Error", ex);
        } catch (JSONException ex) {
            Log.e("CurrencyWidget", "Parse error", ex);
        }
        return rate;
    }

    /**
     * Reads the current rate from droiddraw.org.
     */
    public static class UpdateService extends Service {
        @Override
        public void onStart(Intent intent, int startId) {
            // Build the widget update for today
            RemoteViews updateViews = buildUpdate(this, getRate());

            // Push update for this widget to the home screen
            ComponentName thisWidget = new ComponentName(this, CurrencyWidget.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(thisWidget, updateViews);
        }

        public RemoteViews buildUpdate(Context context, double rate) {
            // Build an update that holds the updated widget contents
            RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);

            // Build the text for the widget
            DecimalFormat format = new DecimalFormat("##.##");
            String euroToDollar = format.format(rate);
            String dollarToEuro = format.format(1 / rate);
            updateViews.setTextViewText(R.id.etod, "Euros to Dollars: " + euroToDollar);
            updateViews.setTextViewText(R.id.dtoe, "Dollars to Euros: " + dollarToEuro);

            // Set up the button click handler
            PendingIntent pendingIntent;
            Intent launchIntent = new Intent(Intent.ACTION_MAIN);
            launchIntent.setClass(context, CurrencyWidget.class);

            pendingIntent = PendingIntent.getActivity(context, 0,   
                    launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            updateViews.setOnClickPendingIntent(R.id.converter, pendingIntent);

            return updateViews; 
        }

        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    }
}


AndroidManifest.xml

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

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".CurrencyWidget" >
            <intent-filter >
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="android.intent.action.MAIN" />

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

        </activity>

        <!-- Service to perform web API queries -->
        <service android:name=".CurrencyWidget$UpdateService" />

        <receiver
            android:label="@string/app_name"
            android:name=".CurrencyWidget" >
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_description" />
        </receiver>
    </application>

    <uses-permission android:name="android.permission.INTERNET" />

</manifest>



res/layout/widget.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget30"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/appwidget_bg" >
       <Button
        android:id="@+id/converter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="Converter" >
    </Button>

    <TextView
        android:id="@+id/dtoe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="&quot;&quot;" >
    </TextView>

    <TextView
        android:id="@+id/etod "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Loading" >
    </TextView>

</RelativeLayout>

/res/xml/widget_description.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dip"
    android:minHeight="72dip"
    android:initialLayout="@layout/widget"
    android:updatePeriodMillis="60000"
    />

LogCat Error

11-25 03:35:06.923: D/AndroidRuntime(351): Shutting down VM
11-25 03:35:06.923: W/dalvikvm(351): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-25 03:35:06.962: E/AndroidRuntime(351): FATAL EXCEPTION: main
11-25 03:35:06.962: E/AndroidRuntime(351): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.kwantlen.android.currencywidget/com.kwantlen.android.currencywidget.CurrencyWidget}: java.lang.ClassCastException: com.kwantlen.android.currencywidget.CurrencyWidget
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.os.Looper.loop(Looper.java:123)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.main(ActivityThread.java:3683)
11-25 03:35:06.962: E/AndroidRuntime(351):  at java.lang.reflect.Method.invokeNative(Native Method)
11-25 03:35:06.962: E/AndroidRuntime(351):  at java.lang.reflect.Method.invoke(Method.java:507)
11-25 03:35:06.962: E/AndroidRuntime(351):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-25 03:35:06.962: E/AndroidRuntime(351):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-25 03:35:06.962: E/AndroidRuntime(351):  at dalvik.system.NativeStart.main(Native Method)
11-25 03:35:06.962: E/AndroidRuntime(351): Caused by: java.lang.ClassCastException: com.kwantlen.android.currencywidget.CurrencyWidget
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
11-25 03:35:06.962: E/AndroidRuntime(351):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
11-25 03:35:06.962: E/AndroidRuntime(351):  ... 11 more

1 个答案:

答案 0 :(得分:0)

CurrencyWidgetAppWidgetProvider,而不是Activity。您正在创建getActivity() PendingIntent,以尝试以CurrencyWidget身份启动Activity。这不起作用。