0

Im getting a Null Pointer Exception error in my AreaURL class. Everything was working fine until i added a Alert Dialog to my onCreate method and i know the error is with my intent due to the fact when i comment it out the action goes through. Here is my code for my 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);
}

}

The part that triggers the Exception is my intent

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

}

Im new to working with Android so any help would be much appreciated.

edit: when i added this in order to check the URL is not null the application displays the correct string

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

edit:logcat is

08-07 12:11:44.453: I/Choreographer(1257): Skipped 126 frames!
The application may be doing too much work on its main thread. 08-07 12:11:46.313: I/Choreographer(1257): Skipped 131 frames!
The application may be doing too much work on its main thread. 08-07 12:11:48.033: I/Choreographer(1257): Skipped 33 frames!
The application may be doing too much work on its main thread. 08-07 12:11:51.753: D/dalvikvm(1257): GC_FOR_ALLOC freed 137K, 6% free 3938K/4152K, paused 146ms, total 146ms 08-07 12:11:52.003: D/AndroidRuntime(1257): Shutting down VM 08-07 12:11:52.003: W/dalvikvm(1257): threadid=1: thread exiting with uncaught exception (group=0xb3a96ba8) 08-07 12:11:52.063: E/AndroidRuntime(1257): FATAL EXCEPTION: main 08-07 12:11:52.063: E/AndroidRuntime(1257): Process: org.me.myandroidstuff, PID: 1257 08-07 12:11:52.063: E/AndroidRuntime(1257): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.me.myandroidstuff/org.me.myandroidstuff.PetrolPriceActivity}: java.lang.NullPointerException 08-07 12:11:52.063: E/AndroidRuntime(1257): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 08-07 12:11:52.063: E/AndroidRuntime(1257): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 08-07 12:11:52.063: E/AndroidRuntime(1257): at android.app.ActivityThread.access$800(ActivityThread.java:135) 08-07 12:11:52.063: E/AndroidRuntime(1257): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 08-07 12:11:52.063: E/AndroidRuntime(1257): at 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): at android.app.ActivityThread.main(ActivityThread.java:5017) 08-07 12:11:52.063: E/AndroidRuntime(1257): at java.lang.reflect.Method.invokeNative(Native Method) 08-07 12:11:52.063: E/AndroidRuntime(1257): at java.lang.reflect.Method.invoke(Method.java:515) 08-07 12:11:52.063: E/AndroidRuntime(1257): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 08-07 12:11:52.063: E/AndroidRuntime(1257): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 08-07 12:11:52.063: E/AndroidRuntime(1257): at dalvik.system.NativeStart.main(Native Method) 08-07 12:11:52.063: E/AndroidRuntime(1257): Caused by: 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): at android.app.Activity.performCreate(Activity.java:5231) 08-07 12:11:52.063: E/AndroidRuntime(1257): at 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 more

my xml layout

<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" />

this my PetrolPriceActivity class

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
}
18
  • 1
    your this inside alert dialog and onclick method should be AreaURL.this Commented Aug 7, 2014 at 16:02
  • no that hasn't worked the exception still occurs when i click the button Commented Aug 7, 2014 at 16:05
  • check your URL I think it returns Null! Commented Aug 7, 2014 at 16:06
  • thats me edited the code with AreaURL.this. Zafer do you mean the newFifthString? when i add a textview to show whats in the string it comes up the correct URL Commented Aug 7, 2014 at 16:06
  • what's is your logcat? Commented Aug 7, 2014 at 16:10

1 Answer 1

2

The error is

errorText.setText(ae.toString());

You are not initializing that variable.

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

}

Sign up to request clarification or add additional context in comments.

20 Comments

Is the same thing like response = (TextView)findViewById(R.id.title);
sorry ehh what would my Id be? response is where the string goes hence why my title textView holds the data recieved by the URL
I think that in your xml layout from the PetrolPriceActivity, you have two edittext, the first is the title, check your xml, what Id are using when declaring the EditText in your layout for the errorText.
okay changing my id to title has fixed the bug but however rather than show my URL i now have a error shown instead. Also my xml layout is different from the layout i posted. i use list.xml for PetrolPriceActivity and testdisplay.xml for my URLArea
well, either add another textView to your layout and only show it when it's needed or append the errorText to response
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.