E / AndroidRuntime(3306):java.lang.RuntimeException:无法启动活动ComponentInfo {c

时间:2011-12-19 09:35:13

标签: android components nullpointerexception

我得到空指针异常。这个错误似乎很常见,但我在网站上找到的所有答案都特定于其他代码中的问题,遗憾的是我在我的代码中无法解决这个问题。

我是android编程的新手。请帮助弄清楚这个程序中的问题。这是代码。

关于我想做什么的一点背景知识。我只是从谷歌财经网络服务获得http响应&将http响应设置为UI中的textView组件

package com.android.myexchange;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MyExchangeActivity extends Activity {
  private Spinner spinner1, spinner2;
  private Button btnSubmit;
  private EditText textbox;
  private TextView result;
  private TextView test;
  private static final String TAG = "MyApp";    

  /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);     

    spinner1 = (Spinner) findViewById(R.id.SpinnerA);
    spinner2 = (Spinner) findViewById(R.id.SpinnerB);
    btnSubmit = (Button) findViewById(R.id.btnSubmit);
    textbox = (EditText) findViewById(R.id.textbox);
    result = (TextView) findViewById(R.id.resulttext);
    textbox.setText("Enter amount");

String testStr=HTTPRequestPoster.sendGetRequest("http://www.google.com/finance/converter",  "a=1&from=USD&to=INR");
    Log.i(TAG, "TEST");
    result.setText(testStr);
    addListenerOnButton(); 
}

private void addListenerOnButton() {

    btnSubmit.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
        Toast.makeText(MyExchangeActivity.this, 
                "OnClickListener : " + 
                "\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) + 
                "\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
            Toast.LENGTH_SHORT).show();

        }
    });
}

}

这是清单xml:          

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

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

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

</manifest>

这是日志:

12-19 21:47:42.403: W/System.err(647): android.os.NetworkOnMainThreadException
12-19 21:47:42.403: W/System.err(647):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
12-19 21:47:42.413: W/System.err(647):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
12-19 21:47:42.413: W/System.err(647):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
12-19 21:47:42.413: W/System.err(647):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
12-19 21:47:42.413: W/System.err(647):  at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
12-19 21:47:42.413: W/System.err(647):  at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
12-19 21:47:42.423: W/System.err(647):  at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
12-19 21:47:42.423: W/System.err(647):  at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
12-19 21:47:42.423: W/System.err(647):  at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
12-19 21:47:42.423: W/System.err(647):  at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
12-19 21:47:42.433: W/System.err(647):  at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
12-19 21:47:42.433: W/System.err(647):  at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
12-19 21:47:42.433: W/System.err(647):  at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
12-19 21:47:42.433: W/System.err(647):  at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
12-19 21:47:42.433: W/System.err(647):  at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
12-19 21:47:42.433: W/System.err(647):  at com.android.myexchange.HTTPRequestPoster.sendGetRequest(HTTPRequestPoster.java:43)
12-19 21:47:42.443: W/System.err(647):  at com.android.myexchange.MyExchangeActivity.onCreate(MyExchangeActivity.java:37)
12-19 21:47:42.443: W/System.err(647):  at android.app.Activity.performCreate(Activity.java:4465)
12-19 21:47:42.443: W/System.err(647):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-19 21:47:42.453: W/System.err(647):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
12-19 21:47:42.463: W/System.err(647):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
12-19 21:47:42.473: W/System.err(647):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
12-19 21:47:42.473: W/System.err(647):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
12-19 21:47:42.473: W/System.err(647):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-19 21:47:42.504: W/System.err(647):  at android.os.Looper.loop(Looper.java:137)
12-19 21:47:42.504: W/System.err(647):  at android.app.ActivityThread.main(ActivityThread.java:4340)
12-19 21:47:42.504: W/System.err(647):  at java.lang.reflect.Method.invokeNative(Native Method)
12-19 21:47:42.513: W/System.err(647):  at java.lang.reflect.Method.invoke(Method.java:511)
12-19 21:47:42.513: W/System.err(647):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-19 21:47:42.513: W/System.err(647):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-19 21:47:42.513: W/System.err(647):  at dalvik.system.NativeStart.main(Native Method)
12-19 21:47:42.513: I/MyApp(647): TEST
12-19 21:47:42.523: D/AndroidRuntime(647): Shutting down VM
12-19 21:47:42.523: W/dalvikvm(647): threadid=1: thread exiting with uncaught exception (group=0x409951f8)
12-19 21:47:42.543: E/AndroidRuntime(647): FATAL EXCEPTION: main
12-19 21:47:42.543: E/AndroidRuntime(647): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.myexchange/com.android.myexchange.MyExchangeActivity}: java.lang.NullPointerException
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.os.Looper.loop(Looper.java:137)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.app.ActivityThread.main(ActivityThread.java:4340)
12-19 21:47:42.543: E/AndroidRuntime(647):  at java.lang.reflect.Method.invokeNative(Native Method)
12-19 21:47:42.543: E/AndroidRuntime(647):  at java.lang.reflect.Method.invoke(Method.java:511)
12-19 21:47:42.543: E/AndroidRuntime(647):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-19 21:47:42.543: E/AndroidRuntime(647):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-19 21:47:42.543: E/AndroidRuntime(647):  at dalvik.system.NativeStart.main(Native Method)
12-19 21:47:42.543: E/AndroidRuntime(647): Caused by: java.lang.NullPointerException
12-19 21:47:42.543: E/AndroidRuntime(647):  at com.android.myexchange.MyExchangeActivity.onCreate(MyExchangeActivity.java:39)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.app.Activity.performCreate(Activity.java:4465)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-19 21:47:42.543: E/AndroidRuntime(647):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
12-19 21:47:42.543: E/AndroidRuntime(647):  ... 11 more

这是布局xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/plain_white_paper"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Spinner
        android:id="@+id/SpinnerA"
        android:layout_width="150dp"
        android:layout_height="43dp"
        android:layout_margin="10dp"
        android:background="#8e99a4"
        android:dropDownWidth="150dp"
        android:entries="@array/currency"
        android:textColor="@android:color/black" />

    <EditText
        android:id="@+id/textbox"
        android:layout_width="135dp"
        android:layout_height="38dp"
        android:background="#8e99a4"
        android:cursorVisible="true"
        android:gravity="center_horizontal"
        android:inputType="number"
        android:text="@string/hello" >

        <requestFocus />
    </EditText>
</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Spinner
        android:id="@+id/SpinnerB"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:background="#8e99a4"
        android:dropDownWidth="150dp"
        android:entries="@array/currency" />

    <TextView
        android:id="@+id/resulttext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_weight="0.68"
        android:background="#8e99a4"
        android:padding="25px"
        android:text="@string/hello" />
</LinearLayout>

<Button
    android:id="@+id/btnSubmit"
    android:layout_width="128dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_margin="10dp"
    android:text="Submit"
    android:textColor="#181f25" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.93"
    android:text="TextView" />

</LinearLayout>

异常发生在日志条目之后,我尝试将http响应文本设置为TextView UI组件。 据我所知,异常发生是因为 result.setText(testStr)有一个我不明白的问题。 HTTPRequestPost.java类工作得很好。我测试了它&amp;它以字符串格式返回httpresponse。如果需要,我可以发布HTTPRequestPost.java的代码。

3 个答案:

答案 0 :(得分:5)

正如您所提到的,HTTPRequestPoster.sendGetRequest()返回null。 这是因为您需要Internet访问权限。将以下行添加到清单文件:

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

您为sendGetRequest()提供的论据完全没问题 只是你的APK需要获得访问互联网的权限。

编辑
StrictMode中,它阻止来自UI线程的网络访问。因此,您需要为网络活动创建单独的线程(或AsyncTask)。 请参阅以下代码:

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

    .....

    new Thread(new Runnable() {

        @Override
        public void run() {
            String testStr=HTTPRequestPoster.sendGetRequest("http://www.google.com/finance/converter",  "a=1&from=USD&to=INR");
            Log.i(TAG, "TEST");
            result.setText(testStr);                
        }
    }).run();
/* String testStr=HTTPRequestPoster.sendGetRequest("http://www.google.com/finance/converter",  "a=1&from=USD&to=INR");
    Log.i(TAG, "TEST");
    result.setText(testStr); */
    addListenerOnButton(); 
}

答案 1 :(得分:0)

之前我收到此错误,但我意识到问题出现在sdk版本中,所以我将sdk版本更改为8并且工作正常,尝试它可能会在没有放置异步任务线程的情况下工作

答案 2 :(得分:-4)

您是否在清单文件中添加了活动名称?

  <application
         -------------------
-----------------------------
            <activity
                android:label="@string/app_name"
                android:name=".MyExchangeActivity" >
            </activity>
-----------------------
------------------
        </application>