Android中的NullPointerException错误:无法实例化

时间:2015-06-09 15:00:55

标签: java android android-activity nullpointerexception

大家好!

我正在努力纠正我在开发Android应用时遇到的这个错误。我试图在模拟器中运行,但它崩溃并给出nullpointerexception错误。然后,我创建了一个新项目,并从头开始将这些文件复制到一个新项目中,仍然是同样的错误。然后,我将应用程序的一部分变成了一个新项目,但它仍然给出了同样的错误。 该错误与启动我正在使用的活动有关。 以下是给定的必要文件,我希望有人可以指导我找到正确的方向并告诉我在做什么错误。 非常感谢!

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

预告文件

<?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错误:

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 个答案:

答案 0 :(得分:2)

把这一行

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

setContentView(R.layout.display_points);

findViewById仅在定义布局后才可用。