NullPointerException error in Android: Unable to instantiate

83 views Asked by At

Hello Everyone!

I am having a hard-time in correcting this error that I am facing while developing an android app. I tried to run in an emulator, but it crashes and gives the nullpointerexception error. Then, I made a new project and from scratch copied those files into a new project, and still the same error. Then, I made a part of the app into a new project, and still it gives the same error. The error is something to do with launching the activity the I am using. Below are the given necessary files, I hope someone can guide me to the right direction and tell what mistake am I doing. Thanks alot!

DISPLAYPOINTS.JAVA

package com.example.safedrive;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.text.Html;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DisplayPoints extends Activity {

    String name = "Ammaar";
    TextView display_points;
    Button btn_start = (Button) findViewById(R.id.btnStart); //Start Button Variable
    String displayPoints;
    InputStream is=null;
    String result=null;
    String line=null;
    int points;
    int code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_points);
        TextView lblName = (TextView) findViewById(R.id.lblName);
        display_points = (TextView) findViewById(R.id.lblCurrPoints); //POINTS TO DISPLAY IN

        lblName.setText(Html.fromHtml("Welcome <b>" + name + "! </b>"));

        new Insert().execute();

        btn_start.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                //MainScreen.IsStarted=true;
                //SpeedPoints start = new SpeedPoints();
                //Intent i = new Intent(getApplicationContext(), SpeedPoints.class);
                //startActivity(i);
                Toast.makeText(getApplicationContext(), "The app has started monitoring your drive...",
                        Toast.LENGTH_LONG).show();
                 //start.startAnimation();
            }
        });


     }

    class Insert extends AsyncTask<String, Void, String> {
            // Do the long-running work in here
            protected String doInBackground(String... args) {
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                nameValuePairs.add(new BasicNameValuePair("fname", name));

                try
                {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://ammar123.net84.net/capstone/displayPoints.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.e("pass 1", "connection success ");
                }
                catch(Exception e)
                {
                    Log.e("Fail 1", e.toString());
                    Toast.makeText(getApplicationContext(), "Invalid IP Address",
                    Toast.LENGTH_LONG).show();
                }     

                try
                {
                    BufferedReader reader = new BufferedReader
                    (new InputStreamReader(is,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                Log.e("pass 2", "connection success ");
                }
                catch(Exception e)
                {
                    Log.e("Fail 2", e.toString());
                }     

            try
            {
                    JSONObject json_data = new JSONObject(result);
                    code=(json_data.getInt("code"));
                    points=(json_data.getInt("pointss"));
                    displayPoints = Integer.toString(points);
            }
            catch(Exception e)
            {
                    Log.e("Fail 3", e.toString());
            }

            return displayPoints;

          }//End of doInBackground method

            protected void onPostExecute(String displaypoints) {

                display_points.setText(displayPoints);
                Toast.makeText(getBaseContext(), "Points Retrieved!",
                        Toast.LENGTH_SHORT).show();

        }//End of onPostExecute
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.display_points, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

MANIFEST FILE

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.safedrive"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.safedrive.DisplayPoints"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

LOGCAT ERRORS:

06-09 18:52:55.467: ERROR/ResourceType(87): Style contains key with bad entry: 0x01010479
06-09 18:52:56.567: ERROR/AndroidRuntime(771): FATAL EXCEPTION: main
06-09 18:52:56.567: ERROR/AndroidRuntime(771): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.safedrive/com.example.safedrive.DisplayPoints}: java.lang.NullPointerException
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.app.ActivityThread.access$600(ActivityThread.java:122)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.os.Looper.loop(Looper.java:137)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.app.ActivityThread.main(ActivityThread.java:4340)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at java.lang.reflect.Method.invokeNative(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at java.lang.reflect.Method.invoke(Method.java:511)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at dalvik.system.NativeStart.main(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): Caused by: java.lang.NullPointerException
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.app.Activity.findViewById(Activity.java:1794)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at com.example.safedrive.DisplayPoints.<init>(DisplayPoints.java:34)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at java.lang.Class.newInstanceImpl(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at java.lang.Class.newInstance(Class.java:1319)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870)
06-09 18:52:56.567: ERROR/AndroidRuntime(771):     ... 11 more
1

There are 1 answers

1
nano_nano On BEST ANSWER

put this line

btn_start = (Button) findViewById(R.id.btnStart); //Start Button Variable

after

setContentView(R.layout.display_points);

findViewById is only possible after the layout is defined.