java - android Intent 空指针异常

标签 java android eclipse android-intent nullpointerexception

我在 AreaURL 类中收到空指针异常错误。一切都工作正常,直到我在 onCreate 方法中添加了一个警报对话框,并且我知道错误是出于我的 Intent ,因为当我将其注释掉时,操作就会完成。这是我的 AreaURL 代码

public class AreaURL extends Activity implements View.OnClickListener{

Button button1;
private String petrolPriceURL = "http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow";

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.userurldisplay);

    button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(this);

}

public void onClick(View v) {

new AlertDialog.Builder(Area.this)
.setTitle("Confirm")
.setMessage("Is this the XML feed you require?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) { 
        // continue
            TestMethod();
        }
    })
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) { 
        // do nothing
    }
 })
.setIcon(android.R.drawable.ic_dialog_alert)
 .show();

}

public void TestMethod(){
    EditText mEdit;
    EditText mEdit2;

    String newFirstString = petrolPriceURL.substring(0,59);
    String newSecondString = petrolPriceURL.substring(63,77);

    mEdit   = (EditText)findViewById(R.id.editText1);
    mEdit.getText().toString();

    mEdit2   = (EditText)findViewById(R.id.editText2);
    mEdit2.getText().toString();

    String newThirdString = newFirstString + mEdit.getText().toString();
    String newFourthString = newSecondString + mEdit2.getText().toString();
    String newFifthString = newThirdString + newFourthString;

    Intent intent=new Intent(this,PetrolPriceActivity.class);
    intent.putExtra("URLString",newFifthString);
    startActivity(intent);
}

}

触发异常的部分是我的 Intent

Intent intent=new Intent(this,PetrolPriceActivity.class);
    intent.putExtra("URLString",newFifthString);
    startActivity(intent);
}

}

我是 Android 使用新手,因此我们将不胜感激。

编辑:当我添加此内容以检查 URL 不为空时,应用程序显示正确的字符串

   response = (TextView)findViewById(R.id.textView2);
    response.setText(newFifthString);

编辑:logcat 是

08-07 12:11:44.453:我/Choreographer(1257):跳过了 126 帧!
应用程序可能在其主线程上做了太多工作。 08-07 12:11:46.313: I/Choreographer(1257): 跳过了 131 帧!
应用程序可能在其主线程上做了太多工作。 08-07 12:11:48.033: I/Choreographer(1257): 跳过了 33 帧!
应用程序可能在其主线程上做了太多工作。 08-07 12:11:51.753: D/dalvikvm(1257): GC_FOR_ALLOC 释放 137K, 6% 释放 3938K/4152K, 暂停 146ms, 总计 146ms 08-07 12:11:52.003:D/AndroidRuntime(1257):关闭虚拟机 08-07 12:11:52.003:W/dalvikvm(1257):threadid = 1:线程因未捕获的异常而退出(组= 0xb3a96ba8) 08-07 12:11:52.063:E/AndroidRuntime(1257):致命异常:主要 08-07 12:11:52.063:E/AndroidRuntime(1257):进程:org.me.myandroidstuff,PID:1257 08-07 12:11:52.063:E/AndroidRuntime(1257):java.lang.RuntimeException:无法启动 Activity ComponentInfo {org.me.myandroidstuff/org.me.myandroidstuff.PetrolPriceActivity}:java.lang.NullPointerException 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.app.ActivityThread.access $ 800(ActivityThread.java:135) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1196) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.os.Handler.dispatchMessage(Handler.java:102) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.os.Looper.loop(Looper.java:136) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.app.ActivityThread.main(ActivityThread.java:5017) 08-07 12:11:52.063:E/AndroidRuntime(1257):在java.lang.reflect.Method.invokeNative( native 方法) 08-07 12:11:52.063:E/AndroidRuntime(1257):在java.lang.reflect.Method.invoke(Method.java:515) 08-07 12:11:52.063:E/AndroidRuntime(1257):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779) 08-07 12:11:52.063:E/AndroidRuntime(1257):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 08-07 12:11:52.063:E/AndroidRuntime(1257):在dalvik.system.NativeStart.main( native 方法) 08-07 12:11:52.063:E/AndroidRuntime(1257):引起:java.lang.NullPointerException 08-07 12:11:52.063:E/AndroidRuntime(1257):在org.me.myandroidstuff.PetrolPriceActivity.onCreate(PetrolPriceActivity.java:53) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.app.Activity.performCreate(Activity.java:5231) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 08-07 12:11:52.063:E/AndroidRuntime(1257):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 08-07 12:11:52.063: E/AndroidRuntime(1257): ... 11 更多

我的 xml 布局

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="invisible"
    android:text="@string/thank_you" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/textView2"
    android:layout_toRightOf="@+id/textView2"
    android:background="#CCCCCC"
    android:ems="10"
    android:inputType="textPersonName" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/textView2"
    android:layout_toRightOf="@+id/textView2"
    android:background="#CCCCCC"
    android:ems="10"
    android:inputType="textPersonName" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/button1"
    android:layout_width="214dp"
    android:layout_height="wrap_content"
    android:text="@string/OK" />

这是我的 PetrolPriceActivity 类

package org.me.myandroidstuff;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class PetrolPriceActivity extends Activity 
{
private TextView response;
private TextView errorText;
private String result;
private String petrolPriceURL;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);

    Bundle extras = getIntent().getExtras();
    if(extras!=null){
        petrolPriceURL =extras.getString("URLString");

    }
    // Get the TextView object on which to display the results
    response = (TextView)findViewById(R.id.title);
    try
    {
        // Get the data from the RSS stream as a string
        result =  petrolPriceString(petrolPriceURL);

        // Do some processing of the data to get the individual parts of the RSS stream
        // At some point put this processing into a separate thread of execution
        // Display the string in the TextView object just to demonstrate this capability
        // This will need to be removed at some point
        response.setText(result);
    }
    catch(IOException ae)
    {
        // Handle error
        response.setText("Error");
        // Add error info to log for diagnostics
        errorText.setText(ae.toString());
    } 

}

// End of onCreate

// Method to handle the reading of the data from the RSS stream
private static String petrolPriceString(String urlString)throws IOException
{
    String result = "";
    InputStream anInStream = null;
    int response = -1;
    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    // Check that the connection can be opened
    if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
    try
    {
        // Open connection
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();
        // Check that connection is Ok
        if (response == HttpURLConnection.HTTP_OK)
        {
            // Connection is OK so open a reader 
            anInStream = httpConn.getInputStream();
            InputStreamReader in= new InputStreamReader(anInStream);
            BufferedReader bin= new BufferedReader(in);

            // Read in the data from the RSS stream
            String line = new String();
            while (( (line = bin.readLine())) != null)
            {
                result = result + "\n" + line;
            }
        }
    }
    catch (Exception ex)
    {
            throw new IOException("Error connecting");
    }

    // Return result as a string for further processing
    return result;
}
// End of petrolPriceString
// End of Activity class
}

最佳答案

错误是

errorText.setText(ae.toString());

您没有初始化该变量。

@Override
public void onCreate(Bundle savedInstanceState) 
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);
    //////////////////////////////////////////////////////Solution
    errorText = (TextView)findViewById(R.id.yourTextView);

    Bundle extras = getIntent().getExtras();
    if(extras!=null){
        petrolPriceURL =extras.getString("URLString");

    }
    // Get the TextView object on which to display the results
    response = (TextView)findViewById(R.id.title);
    try
    {
        // Get the data from the RSS stream as a string
        result =  petrolPriceString(petrolPriceURL);

        // Do some processing of the data to get the individual parts of the RSS stream
        // At some point put this processing into a separate thread of execution
        // Display the string in the TextView object just to demonstrate this capability
        // This will need to be removed at some point
        response.setText(result);
    }
    catch(IOException ae)
    {
        // Handle error
        response.setText("Error");
        // Add error info to log for diagnostics
        errorText.setText(ae.toString()); //////////This variable is not intialized.
    } 

}

关于java - android Intent 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25187097/

相关文章:

安装颠覆性插件后 eclipse (ADT) 主题损坏

java - 如何在 Java 中设置 LDAP 客户端请求的大小限制?

java - 如何为 2 组单选按钮添加 Action 列表

android - 退出应用程序时关闭蓝牙

java - 线程 "main"java.lang.NoClassDefFoundError : org/codehaus/jackson/JsonParseException 中的异常

java - 在spring mvc中保存文件时的tomcat路径

java - 如果我使用 Java 8 库编写应用程序代码并尝试使用 Java 6 编译器编译它,构建是否会/应该失败?

java - 我如何参数化这个 Java 泛型?

java - 编码测试在 Ant 中失败但在 Eclipse 中有效

java - 使用 arrayUnion 将对象添加到 firestore 中的数组