【问题标题】:android intent null pointer exceptionandroid意图空指针异常
【发布时间】:2014-08-07 16:00:13
【问题描述】:

我的 AreaURL 类中出现空指针异常错误。一切正常,直到我在我的 onCreate 方法中添加了一个警报对话框,并且我知道该错误是我的意图,因为当我将其注释掉时,操作会通过。这是我的 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=new Intent(this,PetrolPriceActivity.class);
    intent.putExtra("URLString",newFifthString);
    startActivity(intent);
}

}

我是使用 Android 的新手,因此非常感谢任何帮助。

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

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

edit:logcat 是

08-07 12:11:44.453:I/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): 关闭 VM 08-07 12:11:52.003: W/dalvikvm(1257): threadid=1: 线程以未捕获的异常退出 (group=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: 无法启动活动 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 Method) 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(本机方法) 08-07 12:11:52.063:E/AndroidRuntime(1257):原因:java.lang.NullPointerException 08-07 12:11:52.063: E/AndroidRuntime(1257): at 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
}

【问题讨论】:

  • 你的 this 里面的警告对话框和 onclick 方法应该是 AreaURL.this
  • 没有,当我点击按钮时仍然发生异常
  • 检查你的 URL 我认为它返回 Null!
  • 那是我用 AreaURL.this 编辑的代码。 Zafer 你的意思是 newFifthString 吗?当我添加一个文本视图来显示字符串中的内容时,它会出现正确的 URL
  • 你的 logcat 是什么?

标签: java android eclipse android-intent nullpointerexception


【解决方案1】:

错误是

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

}

【讨论】:

  • 和response一样吗=(TextView)findViewById(R.id.title);
  • 对不起,嗯,我的身份证是什么? response 是字符串所在的位置,因此我的标题 textView 保存了 URL 接收到的数据
  • 我认为在 PetrolPriceActivity 的 xml 布局中,您有两个 edittext,第一个是标题,检查您的 xml,在您的布局中为 errorText 声明 EditText 时使用的 Id。
  • 好吧,将我的 id 更改为 title 已经修复了这个错误,但是我现在没有显示我的 URL,而是显示了一个错误。此外,我的 xml 布局与我发布的布局不同。我为 PetrolPriceActivity 使用 list.xml,为我的 URLArea 使用 testdisplay.xml
  • 好吧,要么在你的布局中添加另一个 textView 并仅在需要时显示它,要么将 errorText 附加到响应中
猜你喜欢
  • 2022-09-23
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多