簡體   English   中英

Android意圖空指針異常

[英]android intent null pointer exception

我在AreaURL類中收到一個Null Pointer Exception錯誤。 一切工作正常,直到我在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不為null時,應用程序顯示正確的字符串

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

編輯: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):at 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(本機方法)08-07 12:11:52.063:E / AndroidRuntime(1257) :由以下原因引起:java.lang.NullPointer 異常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):at 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.
    } 

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM