3

Im getting null pointer exception. This error seems a pretty usual one, but all the answers I found on the site were specific to a problem in others code which unfortunately I cant relate to in my code.

I'm a novice to android programming. Please help figure out the problem in this program. Here's the code.

Little bit of background on what Im trying to do. I'm just getting the http response from the google finance web service & set the http response to the textView component in the UI

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();

        }
    });
}

}

Here's the manifest 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>

Here's the log:

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

Here's the layout 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>

The exception occurs right after the log entry where I try to setText the http response text to TextView UI component. As far as I know the exception is occurring because result.setText(testStr) is having a porblem which I dont understand. The class HTTPRequestPost.java works perfectly fine. Ive tested it & it returns the httpresponse in string format. I can post code of HTTPRequestPost.java if you need it.

Sudhakar
  • 2,904
  • 8
  • 33
  • 47
  • 2
    Welcome to StackOveflow, if you post the stack trace from Logcat, it will be easier to detect the problem, also, please post the layout xml. – MByD Dec 19 '11 at 09:38
  • At which line are you getting the Null pointer exception? Pls post the Log. – Karthik Dec 19 '11 at 09:50
  • 1
    Window->Show view->Other find log cat click on it, turon on application nad post here stack thare where you are getting null pointer (it'll be big red part in logcat) – Robert Dec 19 '11 at 09:57
  • Please post the layout xml also. As you mentioned, the null pointer exception occurs in line 49. So either `result` or `testStr` is null. – Karthik Dec 20 '11 at 04:13
  • @Karthik It looks like **HTTPRequestPoster.sendGetRequest("http://www.google.com/finance/converter", "a=1&from=USD&to=INR")** is returning null. Am i using the method in a wrong way, because I verified the **sendGetRequest()** method of HTTPRequestPoster.java class in a standalone java project & it returns the http response perfectly – Sudhakar Dec 20 '11 at 04:42

3 Answers3

5

As you mentioned, The HTTPRequestPoster.sendGetRequest() returns null. It is because you need Internet access permission. Add the below line to manifest file:

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

The arguments you have given for sendGetRequest() are perfectly fine.
Its just that your APK needs permission to access Internet.

EDIT :
In StrictMode, it blocks network access from UI thread. So you need to create a seperate thread (or AsyncTask) for network activity. See code below:

@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(); 
}
Karthik
  • 3,509
  • 1
  • 20
  • 26
  • 1
    No difference even after adding permissions.Still the same issue – Sudhakar Dec 20 '11 at 05:39
  • 1
    Did you add it before `` tag? It did work for me with permission. Are there some warning Logs (with Tag: _System.err_) shown in Logcat? – Karthik Dec 20 '11 at 05:42
  • 1
    Yes Yes I see System.err. Please take a look at the updated log – Sudhakar Dec 20 '11 at 05:56
  • 1
    That is due to [StrictMode](http://developer.android.com/reference/android/os/StrictMode.html). You can move the `sendGetRequest()` to a Thread. Please see the Edit in my answer. – Karthik Dec 20 '11 at 06:35
  • 1
    aahah! Using AysncTask worked. Thanks a lot @Karthik. Appreciate your time – Sudhakar Dec 20 '11 at 07:08
  • 1
    I have same problem I just moved to AsyncTast and it worked thanks. – sandy Sep 10 '12 at 09:33
0

I got this error before but i realized that the problem was in sdk version, so i changed the sdk version to 8 and it worked, try it maybe it will work without putting async task thread

Amr Ashraf
  • 315
  • 4
  • 14
-4

Did you add the activity name in the manifest file?

  <application
         -------------------
-----------------------------
            <activity
                android:label="@string/app_name"
                android:name=".MyExchangeActivity" >
            </activity>
-----------------------
------------------
        </application>
jainal
  • 2,973
  • 2
  • 20
  • 18
  • Its a Null Pointer Exception. It would not be related to the manifiest file change you have mentioned. – Karthik Dec 19 '11 at 09:54